admin管理员组

文章数量:1192806

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.

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.

Share Improve this question edited Jan 24, 2012 at 17:19 No Results Found 103k38 gold badges198 silver badges231 bronze badges asked Jan 24, 2012 at 17:15 JonasJonas 1,0694 gold badges20 silver badges33 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 21

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

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.

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

Use the setInterval function.

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

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

本文标签: javascriptHow can I call a function every 3 seconds for 15 secondsStack Overflow