javascript timer loop

2019-01-18 18:01发布

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.

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

2条回答
祖国的老花朵
2楼-- · 2019-01-18 18:38

I agree with keyboardP that you should probably be using setInterval instead 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:

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:

setTimeout(instance, 100);

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

查看更多
【Aperson】
3楼-- · 2019-01-18 18:42

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

setInterval(myMethod, 5000);

function myMethod( )
{
  //this will repeat every 5 seconds
  //you can reset counter here
}
查看更多
登录 后发表回答