Intervals

Avatar of Chris Coyier
Chris Coyier on

Standard

You don’t need to create the variable, but it’s a good practice as you can use that variable with clearInterval to stop the currently running interval.

var int = setInterval("doSomething()", 5000 ); /* 5 seconds */
var int = setInterval(doSomething, 5000 ); /* same thing, no quotes, no parens */

If you need to pass parameters to the doSomething function, you can pass them as additional parameters beyond the first two to setInterval.

Without overlapping

setInterval, as above, will run every 5 seconds (or whatever you set it to) no matter what. Even if the function doSomething takes long than 5 seconds to run. That can create issues. If you just want to make sure there is that pause in between runnings of doSomething, you can do this:

(function(){

   doSomething();

   setTimeout(arguments.callee, 5000);

})()