How can I call a function every 3 seconds for 15 seconds?

How can I call the jQuery function every 3 seconds?

$(document).ready(function ()
{
    //do stuff...

    $('post').each(function()
    {
        //do stuff...
    })

    //do stuff...
})

I am trying to run this code for 15 seconds.

+5
source share
5 answers

None of the answers still takes into account that he wants only 15 seconds and then stops ...

$(function() {
    var intervalID = setInterval(function() {
        //  Do whatever in here that happens every 3 seconds
    }, 3000);
    setTimeout(function() {
        clearInterval(intervalID);
    }, 18000);
});

This creates an interval (every 3 seconds) that runs any code that you enter into the function. After 15 seconds, the interval is destroyed (the initial 3-second delay, therefore, the total execution time is 18 seconds).

+11
source

You can use setTimeoutto start the function after passing X milliseconds.

var timeout = setTimeout(function(){
    $('post').each(function(){
        //do stuff...
    });
}, 3000);

Or, setIntervalto run a function every X milliseconds.

var interval = setInterval(function(){
    $('post').each(function(){
        //do stuff...
    });
}, 3000);

setTimeout setInterval , -/ clearTimeout clearInterval.

+1

You can also use the setTimeout method, which supports features such as canceling a timer.

See: http://msdn.microsoft.com/en-us/library/ie/ms536753(v=vs.85).aspx

0
source
setInterval(function() {
      // Do something every 3 seconds
}, 3000);
0
source

Use the function setInterval.

var doPost = function() {
  $('post').each(function() { 
    ...
  });
};
setInterval(function() { doPost(); }, 3000);
0
source

All Articles