0

I have built an app to track time uisng electron and react.

You can see the difference between hubstaff and the other software. I hit start at the exact same time but there is few minutes difference, at first we don't see it but after a certain amount of time the difference is displayed.

It's quite strange and i cannot figure out what the problem is. 1 seconds should be 1 second probably the setInterval cause delay by few ms when running?

enter image description here

   {timer && <img src={pause} className="play" onClick={handleStartToggle} />}
   {!timer && <img src={play} className="play" onClick={handleStartToggle} />}

Then

  useEffect(() => {
    if (seconds > 0 && timer) {
      axios({
        method: "POST",
        url: process.env.REACT_APP_API_URL + '/desktop/track',
        headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Headers": "*", "Access-Control-Allow-Origin": "*", "Accept": "application/json" },
        data: {
          activeTask: activeTaskTimer,
          activeClient: activeClientTimer,
          user: userData,
          seconds: seconds
        }
      })
        .then(result => {
          if (result.data.json.error == false) {
            activeClientTimer.seconds_tracked = result.data.json.seconds_tracked; // seconds
            var sessionTimer = sessionStorage.getItem("timer");
            var sessionTimer = JSON.parse(sessionTimer);
            if (sessionTimer.timer == 0 || sessionTimer.company_id == null || sessionTimer.company_id == '') {
              const timerDataSession = {
                timer: 1,
                timer_id: result.data.json.timer_id,
                company_id: result.data.json.company_id
              };
              sessionStorage.setItem('timer', JSON.stringify(timerDataSession));
            }
          } else {
            setActiveTaskTimer([]);
            setActiveClientTimer([]);
            clearInterval(timer);   // <-- Change here
            setTimer(false);
            const timerDataSession = {
              timer: 0,
              timer_id: '',
              company_id: ''
            };
            sessionStorage.setItem('timer', JSON.stringify(timerDataSession));
            alert(result.data.json.message);
          }
        })
        .catch(error => {
          console.log(error);
        })
    }
  }, [seconds, userData]);

  const handleStartToggle = () => {

    // Start new timer only if it's not run yet
    let timerInterval = null;
    if (timerInterval && activeTask.id) {

      setActiveTaskTimer(activeTask);
      setActiveClientTimer(activeClient);

      timerInterval = setInterval(() => {
        console.info(">Timer ", seconds, new Date().toLocaleString())
        setSeconds((current) => current + 1);
        const newObjActiveTask = activeTask;
        newObjActiveTask.seconds_tracked = newObjActiveTask.seconds_tracked + 1;
        setActiveTask(newObjActiveTask);
      }, 1000);

      // Else, it's already running, we stop it and reset
    } else {
      setActiveTaskTimer([]);
      setActiveClientTimer([]);
      if (timerInterval) {
        clearInterval(timerInterval); // <-- Change here
      }
      setTimer(false);
      const timerDataSession = {
        timer: 0,
        timer_id: '',
        company_id: ''
      };
      sessionStorage.setItem('timer', JSON.stringify(timerDataSession));
    }
  }
Brian Millot
  • 179
  • 1
  • 12
  • 4
    Timers are throttled when the page is in background. This is to save battery and trees. After all, why would you need anything to be updated every second while not looking at the page. If you want a reliable timer, check the current time at every iteration. – Kaiido Sep 27 '22 at 06:22
  • 1
    `setInterval` and `setTimeout` do not guarantee that their callbacks are executed after exact the time `x` you've specified. It's a _"execute the callbacks as soon as possible after `x` milliseconds have passed"_ – Andreas Sep 27 '22 at 06:34
  • Thanks Guys, do you have any example using current time as per Kaiido suggestion? – Brian Millot Sep 27 '22 at 06:37

0 Answers0