How can I repeat a function doSomething()
every 5 seconds.
I also need code that will make it stop doing it.
And code to on-the-fly adjust the frequency.
How do I delay a function call for 5 seconds? A setTimeout is a native JavaScript function, which calls a function or executes a code snippet after a specified delay (in milliseconds). A setTimeout accepts a reference to a function as the first argument. Alert messages will pop up after 5 seconds automatically.
You can use setInterval() , the arguments are the same.
The stop() method works for all jQuery effect functions, including sliding, fading and custom animations. Syntax: $(selector). stop(stopAll,goToEnd);
setTimeout() will only launch the command once. In this case, setInterval() is your friend.
var iFrequency = 5000; // expressed in miliseconds var myInterval = 0; // STARTS and Resets the loop if any function startLoop() { if(myInterval > 0) clearInterval(myInterval); // stop myInterval = setInterval( "doSomething()", iFrequency ); // run } function doSomething() { // (do something here) }
from code...
<input type="button" onclick="iFrequency+=1000; startLoop(); return false;" value="Add 1 second more to the interval" />
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