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

JavascriptDom Events

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

> 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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

Solution 4 - Javascript

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.

Solution 5 - 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

Solution 6 - Javascript

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

Here is a decent tutorial article.

Solution 7 - Javascript

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

Solution 8 - Javascript

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

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncoderexView Question on Stackoverflow
Solution 1 - JavascriptzombatView Answer on Stackoverflow
Solution 2 - JavascriptMatt CoubroughView Answer on Stackoverflow
Solution 3 - JavascriptgnarfView Answer on Stackoverflow
Solution 4 - JavascriptOnur YıldırımView Answer on Stackoverflow
Solution 5 - JavascriptRuss CamView Answer on Stackoverflow
Solution 6 - JavascriptMatthew VinesView Answer on Stackoverflow
Solution 7 - JavascriptBen LeshView Answer on Stackoverflow
Solution 8 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 9 - JavascriptNelsonView Answer on Stackoverflow