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

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.

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

  /// call your function here
}, 5000);

To stop the loop you can use


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

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

Just a little tip for the first answer. If your function is already defined, reference the function but don't call it!!! So don't put any parentheses after the function name. Just like:


A good exemple where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

function myTimer() {
    console.log(' each 1 second...');

var myVar = setInterval(myTimer, 1000);

call this line to stop the loop:


The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete

(function runForever(){
  // Do something here
  setTimeout(runForever, 5000)

// Regular function with arguments
function someFunction(file, directory){
  // Do something here
  setTimeout(someFunction, 5000, file, directory)
  // YES, setTimeout passes any extra args to
  // function being called

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 suites you most and how to stop each of them.

you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)

  var time = 3670;

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    document.getElementById("demo").innerHTML = "EXPIRED";

}, 1000);