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/
Use setInterval() to do the timer loop in JavaScript. It will repeat automatically until you clear the interval. setTimeout will execute the code once, after the timeout. setInterval will execute the code forever, in intervals of the provided timeout.
There are two timer functions in JavaScript: setTimeout() and setInterval() . The following section will show you how to create timers to delay code execution as well as how to perform one or more actions repeatedly using these functions in JavaScript.
The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.
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 }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With