Javascript javascript定时器循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8663246/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:57:46  来源:igfitidea点击:

javascript timer loop

javascripttimer

提问by stursby

I want to create a timer that once it reaches a certain point, the timer resets, and then starts over.

我想创建一个计时器,一旦达到某个点,计时器就会重置,然后重新开始。

Right now, I've got the loop set up, and as a test I want it to reset after 5000 ms (5 seconds). But the counter goes all haywire.

现在,我已经设置了循环,作为测试,我希望它在 5000 毫秒(5 秒)后重置。但是柜台完全出问题了。

WIP Demo here: http://jsfiddle.net/stursby/wUHA3/

WIP 演示在这里:http: //jsfiddle.net/stursby/wUHA3/

回答by keyboardP

Instead of setTimeout, consider using setInterval. It will repeat automatically until you clear the interval.

考虑使用 setInterval 代替 setTimeout。它会自动重复,直到您清除间隔。

setInterval(myMethod, 5000);

function myMethod( )
{
  //this will repeat every 5 seconds
  //you can reset counter here
}

回答by Chad

I agree with keyboardP that you should probably be using setIntervalinstead of setTimeout. However, to answer your original question the reason you are having issues with the timer is because of your repetition logic. Don't use:

我同意您可能应该使用的 keyboardPsetInterval而不是setTimeout. 但是,要回答您的原始问题,您遇到计时器问题的原因是您的重复逻辑。不要使用:

var diff = (new Date().getTime() - start) - time;
window.setTimeout(instance, (100 - diff));

You don't need to try and account for execution time (which I assume is what you were trying to do with diff). Just assume it is negligible and use:

您不需要尝试考虑执行时间(我认为这就是您尝试使用的时间diff)。假设它可以忽略不计并使用:

setTimeout(instance, 100);

And your issue is resolved, as you can see in this jsFiddle.

您的问题已解决,正如您在此 jsFiddle 中所见