Can I do this using jQuery or should I be looking at using something else?
-
Short answer: The same as in JavaScript ;) (there is no special jQuery functionality for that). – Felix Kling Jan 11 '11 at 00:59
-
4No need for jQuery. Plain old `setInterval()` will do – Pekka Jan 11 '11 at 01:00
-
1possible duplicate of [setInterval vs setTimeout](http://stackoverflow.com/questions/2696692/setinterval-vs-settimeout) – treeface Jan 11 '11 at 01:00
4 Answers
The jQuery.delay()
function is designed to delay execution of functions in the jQuery queue.
There is already a built-in Javascript function for handling interval functionality, you wouldn't use jQuery to achieve that.
setInterval(function() {
alert("Message to alert every 5 seconds");
}, 5000);

- 22,803
- 16
- 52
- 80
Again, no need for jQuery here:
setInterval(function() {
alert("How Now Brown Cow");
}, 5000);
(Don't tell anyone, but @Justin Niessner is right, jQuery is JavaScript)

- 161,348
- 33
- 346
- 320
-
2
-
2Technically, you can do EVERYTHING in vanilla JavaScript that you would use jQuery for since jQuery IS JavaScript. – Justin Niessner Jan 11 '11 at 01:10
-
I agree, jQuery is really the best, it solves all kinds of browser problems and is good, as well – goat Jan 11 '11 at 01:29
You can either use setInterval()
or setTimeout()
. There may be a jQuery specific helper function as well.
setInterval()
takes 2 parameters - a function to execute, and the delay in milliseconds between calls. It will keep calling the function until you change or pages or call clearInterval(intervalID)
. You have to pass in the value returned by setInterval()
to clear it.
setTimeout()
takes the same parameters, but it will only execute once. You can get around that by having the last line in the function you pass to setTimeout()
call setTimeout()
again.
I've noticed that in some browsers, you're restricted in what you can do with setInterval()
- for instance, it might not let you call setInterval()
on page load.

- 17,560
- 3
- 48
- 51
I use this script Cookbook/wait with a small plugin and it works pretty well:
(function($){
$.fn.runItIf = function(ex, fn, args) {
var self = this;
return $(self).queue(function() {
args = args || [];
if (ex)
fn.apply.(self, args );
$(self).dequeue();
});
};
$.fn.runIt = function(fn, args) {
return $(this).runItIf(true, fn, args);
};
$.fn.wait = function(time, type) {
time = time || 1000;
type = type || "fx";
return this.queue(type, function() {
var self = this;
setTimeout(function() {
$(self).dequeue();
}, time);
});
};
})(jQuery);
Example based on the example in Cookbook/wait:
function runIt() {
var expression = true;
$("div").wait()
.animate({left:'+=200'},2000)
.runIt(function() { /* ... */ } ).wait(10)
.runItIf(expression, function() { /* ... */ } ).wait(10)
.animate({left:'-=200'},1500,runIt);
}
runIt();

- 14,887
- 13
- 64
- 115