Reputation: 1069
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
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
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
Reputation: 755397
Use the setInterval
function.
var doPost = function() {
$('post').each(function() {
...
});
};
setInterval(function() { doPost(); }, 3000);
Upvotes: 0
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