Grow your CSS skills. Land your dream job.

Last updated on:

Intervals

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

})()

Reference URL

Comments

  1. Always use:

    var int = window.setInterval("doSomething()", 5000) ;

    instead of just:

    var int = setInterval("doSomething()", 5000);

    This also applies to other functions:

    
    window.clearInterval
    window.setTimeout
    window.clearTimeout
    

Leave a Comment

Current day month ye@r *

*May or may not contain any actual "CSS" or "Tricks".