Is there any way to call a function periodically in JavaScript?
9 Answers
The
setInterval()
method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
var intervalId = setInterval(function() {
alert("Interval reached every 5s")
}, 5000);
// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);
See more @ setInterval() @ MDN Web Docs

- 18,137
- 13
- 50
- 91

- 92,731
- 24
- 156
- 164
-
Worth noting that `setInterval` waits the interval period before calling the given function for the first time. – ComDubh May 23 '21 at 10:11
Please note that setInterval() is often not the best solution for periodic execution - It really depends on what javascript you're actually calling periodically.
eg. If you use setInterval() with a period of 1000ms and in the periodic function you make an ajax call that occasionally takes 2 seconds to return you will be making another ajax call before the first response gets back. This is usually undesirable.
Many libraries have periodic methods that protect against the pitfalls of using setInterval naively such as the Prototype example given by Nelson.
To achieve more robust periodic execution with a function that has a jQuery ajax call in it, consider something like this:
function myPeriodicMethod() {
$.ajax({
url: ...,
success: function(data) {
...
},
complete: function() {
// schedule the next request *only* when the current one is complete:
setTimeout(myPeriodicMethod, 1000);
}
});
}
// schedule the first invocation:
setTimeout(myPeriodicMethod, 1000);
Another approach is to use setTimeout but track elapsed time in a variable and then set the timeout delay on each invocation dynamically to execute a function as close to the desired interval as possible but never faster than you can get responses back.

- 3,739
- 2
- 26
- 40
-
1setTimeout(myPeriodicMethod, 1000); is called 2 times. is it requred? I think set time out should be called only in the complete function – Vishnudev K Aug 06 '14 at 11:53
-
1Yes the second setTimeout() isn't a requirement, you could simply call myPeriodicMethod() which would perform the first ajax call immediately... but if you want to *schedule it* with a delay from the very first call you could write it as I have written. – Matt Coubrough Aug 06 '14 at 21:12
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);

- 105,192
- 25
- 127
- 161
-
3+1 If you're a student of the [Crockford school of JavaScript](http://javascript.crockford.com/code.html), you avoid eval in all its evil forms. – Patrick McElhaney Aug 03 '09 at 20:47
-
@Patrick - I don't think the "Do not use $ (dollar sign) or \ (backslash) in names" suggestion will go down well with the jQuery lot :) – Russ Cam Aug 03 '09 at 22:11
Old question but.. I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
TaskTimer
works both in browser and Node. See documentation for all features.

- 32,327
- 12
- 84
- 98
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.

- 27,253
- 7
- 76
- 97
Since you want the function to be executed periodically, use setInterval

- 807,428
- 183
- 922
- 838
function test() {
alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
clearInterval(id);
}

- 107,825
- 47
- 247
- 232
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."

- 464
- 4
- 10