[javascript] Is there any way to call a function periodically in JavaScript?

Is there any way to call a function periodically in JavaScript?

This question is related to javascript dom-events

The answer is


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."


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.


You will want to have a look at setInterval() and setTimeout().

Here is a decent tutorial article.


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);

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


Since you want the function to be executed periodically, use setInterval


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

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.