javascript setInterval未按时运行 [英] javascript setInterval not running on time

查看:74
本文介绍了javascript setInterval未按时运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个无法正常工作的计时器方法。它应该显示在表单上经过的时间,但它按2或3计数而不是每秒计数一次。什么可能导致这种行为,我该如何解决?

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?

我的代码:

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

上面的代码显示表格时间:00:01然后表格时间:00:04然后表格时间:00:07等。

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

推荐答案

以下是我的一个例子想出了。它使用时间,以便不依赖于 setInterval 的准确性。希望这会有所帮助!

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();

这篇关于javascript setInterval未按时运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆