本文介绍了JS - 计时器运行缓慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个简单的JavaScript计时器,但我注意到它以1/3的速度运行。该计时器用于跟踪已经过多少MS。我不确定我做错了什么。



  time = 10000; 
timer = setInterval(function(){
time--;
$('#timer')。text(time);
},1);


解决方案

您的错误是假设您的计算机可以保留计时器一些浏览器将使用计算机的时钟,在Windows中每隔16ms(1/60秒,即屏幕的帧速率)进行计时。其他人会以3ms更精确的方式覆盖它,这就是为什么你看到1/3速度的结果。



相反,使用Delta Timing:

  var start = new Date()。getTime(); 
setInterval(function(){
var now = new Date()。getTime();
var elapsed = now-start;
var timeleft = 10000-elapsed;
$(#timer)。text(timeleft);
},25);


I have written a simple JavaScript timer, but I've noticed that it runs at 1/3 speed. This timer is suppose to keep track how many MS has passed. I am unsure what I have done incorrectly.

http://jsfiddle.net/m3vYc/

time = 10000;
timer = setInterval( function() {
    time--;
    $('#timer').text(time);
}, 1);
解决方案

Your error is in assuming that your computer can keep timers of 1 millisecond.

Some browsers will use the computer's clock, which in Windows ticks every 16ms (1/60th of a second, ie the framerate of your screen). Others will override this for a somewhat more accurate 3ms, which is why you are seeing a result of 1/3 speed.

Instead, use Delta Timing:

var start = new Date().getTime();
setInterval(function() {
    var now = new Date().getTime();
    var elapsed = now-start;
    var timeleft = 10000-elapsed; 
    $("#timer").text(timeleft);
},25);

Demo

这篇关于JS - 计时器运行缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 21:01