By Sam Deering

JavaScript setInterval() Function Examples

By Sam Deering

The JavaScript setInterval function can be used to automate a task using a regular time based trigger. Just to be clear, setInterval() is a native JavaScript function.

This function is very similar to the jQuery setTimeout() Function.

Basic setInterval() Example

setInterval(function() {
      // Do something every 5 seconds
}, 5000);

Tips: If your changing images dynamically load variables from a PHP script you will need to add some sort of random number to the script so that it forces a refresh in all browsers. You can do this by using the following code to generate a random number.

    var refreshId = setInterval( function() 
        var r = (-0.5)+(Math.random()*(1000.99));
    }, 5000);

Tips: You might also have to use the ajax method instead of load, to prevent the AJAX request to be cached.
Tips: Alternatively, you could stick header(“Cache-Control: no-cache, must-revalidate”); towards the top of your random.php file to prevent the browser from caching.

  • Chris

    Just an FYI to save cionfusion for people later on…


    The jQuery setInterval function

    setInterval isn’t a jQuery function it is a native function of Javascript!

  • just a clean example… but as already said setinterval is javascript native function

  • Greg

    Yeah, seriously, setTimeout() and setInterval() have nothing to do with jQuery… They are pure vanilla JavaScript, available long before jQuery was even a thought.

    Also, fix the formatting on your second example. Line 3 should be indented another level.

    • jquery4u

      @Greg – thanks for the constructive comments. Code indentation fixed up.
      @Chris, Nepal – noted.

  • Elwood

    Still Helpful

  • Nic Johnson

    Hi there, thanks for the code, but setInterval and setTimeout are not jQuery functions, they’re just plain old JavaScript. Still useful though.

  • Mike

    I think we need one more comment explaining that this isn’t jQuery.

  • 416

    ohhhhh i think setInterval is not a jquery function LOL since noone mentioned it……….

  • Prabu Govindsamy

    the setinterval() is getting called when app is minimized in ios simulator why is that so ?

  • Hi,
    How can i use setInterval() in for loop
    for(i=0; i<100; i++)
    jQuery('.class).css('hieght', i+'%');
    I want to increase i's value after 100 milliseconds.
    how can i do this?please let me know.
    Thanks in advance.

  • sai

    can u plz tell me……

    how can i

    add multiple images for every second on mouse hover …..


    I was expecting this to generate time every second, but it does it once without repeat, am I missing something?

    setInterval(function() {

    // Do something every 1 seconds


    }, 1000);

Get the latest in JavaScript, once a week, for free.