Is there any way to call a function periodically in JavaScript.
yes - take a look at setInterval
and setTimeout
for executing code at certain times. setInterval would be the one to use to execute code periodically.
See a demo and answer here for usage
You will want to have a look at setInterval() and setTimeout().
Here is a decent tutorial article.
Since you want the function to be executed periodically, use setInterval
You want setInterval()
:
var intervalID = setInterval(function(){alert("Interval reached");}, 5000);
The first parameter to setInterval() can also be a string of code to be evaluated.
You can clear a periodic function with:
clearInterval(intervalID);
function test() {
alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
clearInterval(id);
}
Everyone has a setTimeout/setInterval solution already. I think that it is important to note that you can pass functions to setInterval, not just strings. Its actually probably a little "safer" to pass real functions instead of strings that will be "evaled" to those functions.
// example 1
function test() {
alert('called');
}
var interval = setInterval(test, 10000);
Or:
// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);
The native way is indeed setInterval()
/clearInterval()
, but if you are already using the Prototype library you can take advantage of PeriodicalExecutor:
new PeriodicalUpdator(myEvent, seconds);
This prevents overlapping calls. From http://www.prototypejs.org/api/periodicalExecuter:
"it shields you against multiple parallel executions of the callback function, should it take longer than the given interval to execute (it maintains an internal “running” flag, which is shielded against exceptions in the callback function). This is especially useful if you use one to interact with the user at given intervals (e.g. use a prompt or confirm call): this will avoid multiple message boxes all waiting to be actioned."