What's the easiest way to call a function every 5 seconds in jQuery?

Viewed 681286

JQuery, how to call a function every 5 seconds.

I'm looking for a way to automate the changing of images in a slideshow.

I'd rather not install any other 3rd party plugins if possible.

7 Answers

You don't need jquery for this, in plain javascript, the following will work!

var intervalId = window.setInterval(function(){
  /// call your function here
}, 5000);

To stop the loop you can use

clearInterval(intervalId) 

you could register an interval on the page using setInterval, ie:

setInterval(function(){ 
    //code goes here that will be run every 5 seconds.    
}, 5000);

Both setInterval and setTimeout can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suits you most and how to stop each of them.

Related