Jonas
Jonas

Reputation: 1069

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

How do I call a jQuery function every 3 seconds?

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

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

    //do stuff...
})

I'm trying to run that code for a period of 15 seconds.

Upvotes: 7

Views: 20695

Answers (5)

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26153

None of the answers so far take into account that it only wants to happen for 15 seconds and then stop...

$(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 whatever code you put in the function. After 15 seconds the interval is destroyed (there is an initial 3 second delay, hence the 18 second overall runtime).

Upvotes: 21

gen_Eric
gen_Eric

Reputation: 227310

You can use setTimeout to run a function after X milliseconds have passed.

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

Or, setInterval to run a function every X milliseconds.

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

setTimeout and setInterval return IDs, these can be used to clear the timeout/interval using clearTimeout or clearInterval.

Upvotes: 2

JaredPar
JaredPar

Reputation: 755397

Use the setInterval function.

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

Upvotes: 0

Johan
Johan

Reputation: 35213

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

Upvotes: 0

Simon
Simon

Reputation: 5503

You could use the setTimeout method also, which supports things like cancelling the timer.

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

Upvotes: -1

Related Questions