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/
I agree with keyboardP that you should probably be using
setInterval
instead ofsetTimeout
. However, to answer your original question the reason you are having issues with the timer is because of your repetition logic. Don't use: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:And your issue is resolved, as you can see in this jsFiddle.
Instead of setTimeout, consider using setInterval. It will repeat automatically until you clear the interval.