Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript setInterval not running on time

I've written a timer method which isn't working correctly. It is supposed to display the time elapsed while on a form, but it is counting by 2's or 3's instead of once per second. What could cause this behavior and how can I fix it?

My code:

function startTimer() {
  var minutes, seconds;
  
  setInterval(function () {
    if (!isPaused) {
      minutes = parseInt(timer / 60, 10);
      seconds = parseInt(timer % 60, 10);
      
      minutes = minutes < 10 ? "0" + minutes : minutes;
      seconds = seconds < 10 ? "0" + seconds : seconds;
      
      $('#TimeLabel').text("Form Time: " + minutes + ":" + seconds);
      
      ++timer;
    }
  }, 1000);
}

The above code displays "Form Time: 00:01" then "Form Time: 00:04" then "Form Time:00:07" ect.

like image 885
BrianLegg Avatar asked Dec 18 '15 16:12

BrianLegg


1 Answers

Here's an example of what I came up with. It uses time so as not to be dependent on the accuracy of your setInterval. Hope this helps!

function startTimer(){
        var minutes,
            seconds;

        var startTime = new Date;

        setInterval(function(){

            var currentTime = new Date;
            seconds = currentTime.getSeconds() - startTime.getSeconds();

            if(seconds < 0){
                seconds += 60;
            }else if(seconds === 0){
                minutes = currentTime.getMinutes() - startTime.getMinutes();
            }

            console.log(minutes + ':' + seconds);

        }, 100);
}
startTimer();
like image 150
Antonio Manente Avatar answered Sep 30 '22 15:09

Antonio Manente