Calling a function every 60 seconds

Richard Knop picture Richard Knop · Jun 29, 2010 · Viewed 431.7k times · Source

Using setTimeout() it is possible to launch a function at a specified time:

setTimeout(function, 60000);

But what if I would like to launch the function multiple times? Every time a time interval passes, I would like to execute the function (every 60 seconds, let's say).

Answer

jAndy picture jAndy · Jun 29, 2010

If you don't care if the code within the timer may take longer than your interval, use setInterval():

setInterval(function, delay)

That fires the function passed in as first parameter over and over.

A better approach is, to use setTimeout along with a self-executing anonymous function:

(function(){
    // do some stuff
    setTimeout(arguments.callee, 60000);
})();

that guarantees, that the next call is not made before your code was executed. I used arguments.callee in this example as function reference. It's a better way to give the function a name and call that within setTimeout because arguments.callee is deprecated in ecmascript 5.