views:

109

answers:

5

Using setTimeout() it is possible to launch a function at specified time, e.g.:

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

+2  A: 

use the

setInterval(function, 60000);
Muneer
+2  A: 
setInterval(fn,time)

is the method you're after.

Jamiec
+4  A: 

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.

jAndy
It's not possible for the next call to be made before the code finishes executing. The timer counts down asynchronously but the callback has to be queued. This means that your callback may (and probably will) fire after more than 60 seconds.
Andy E
The difference is that setInterval will generally run the function x milliseconds after the **start** of the previous iteration, whereas the approach here will run the next iteration x milliseconds after the previous one **ended**
Gareth
@Andy E's head, @Gareth: Gareth is right, that approach just avoids that loop-code will executed while another codeblock is still running.
jAndy
@jAndy: True enough, you edited your answer after I wrote/while I was writing my comment. What I said still stands though, there's no danger of the next callback executing before the previous one has finished.
Andy E
+1  A: 

Or use this jQuery plugin

Icebob
A: 

use setInterval(fn,time)

christian louboutin sale