stursby
stursby

Reputation: 879

javascript timer loop

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/

Upvotes: 46

Views: 117323

Answers (2)

Chad
Chad

Reputation: 19609

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.

Upvotes: 6

keyboardP
keyboardP

Reputation: 69372

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
}

Upvotes: 93

Related Questions