Javascript setInterval not working on time

I wrote a timer method that does not work correctly. It should display the elapsed time during the form, but it is counted at 2 or 3 instead of once per second. What can cause this behavior and how to fix it?

My code is:

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);
}
Run code

In the above code, “Form Time: 00:01” is displayed, then “Form Time: 00:04”, then “Form Time: 00: 07”, etc.

+4
source share
4 answers

Here is an example of what I came up with. It uses time to not depend 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();
+3
source

javascript , .

, , , , .

, : setTimeout setInterval delay time, .

, window.setTimeout(function() { console.log('Hello World'); }, 1000); , 1000 (1 ).

, 100 , , .

0

, , :

  var timer =1;
  var minutes, seconds;

  setInterval(function () {

  minutes = parseInt(timer / 60, 10);
  seconds = parseInt(timer % 60, 10);

  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;

  console.log("Form Time: " + minutes + ":" + seconds);

  ++timer;
  }, 1000);

So there might be something that increases the value of the timer or ensures that your startTimer function is called only once.

-1
source

The problem may have something to do with not declaring all your variables. When I run this version in the console, it works correctly:

function startTimer() {
  var minutes, seconds, isPaused = false, timer = 1;
  
  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;
      
      console.log("Form Time: " + minutes + ":" + seconds);
      
      timer++;
    }
  }, 1000);
}

startTimer();
Run code
-1
source

Source: https://habr.com/ru/post/1620783/


All Articles