Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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/

like image 824
stursby Avatar asked Dec 29 '11 01:12

stursby


People also ask

How do you make a timed loop in JavaScript?

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.

Does JavaScript have a timer function?

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.

How do you set an interval timer?

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.


2 Answers

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 } 
like image 52
keyboardP Avatar answered Sep 28 '22 19:09

keyboardP


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.

like image 31
Chad Avatar answered Sep 28 '22 19:09

Chad