Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do something every 5 seconds and the code to stop it. (JQuery)

Tags:

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.

like image 605
steven Avatar asked Oct 09 '09 07:10

steven


People also ask

How can we delay calling a function after 5 seconds?

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.

How can we call a function which logs a message after every 5 seconds?

You can use setInterval() , the arguments are the same.

How do I stop a jQuery from running?

The stop() method works for all jQuery effect functions, including sliding, fading and custom animations. Syntax: $(selector). stop(stopAll,goToEnd);


1 Answers

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" /> 
like image 137
pixeline Avatar answered Sep 28 '22 06:09

pixeline