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

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

This question already has an answer here:

Calling a function every 60 seconds

11 answers

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.

Solutions/Answers:

Solution 1:

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

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

To stop the loop you can use

clearInterval() 

Solution 2:

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

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

Solution 3:

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:

my_function(){};
setInterval(my_function,10000);

Solution 4:

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

// IIFE
(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
}

Solution 5:

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:

 clearInterval(myVar);

Solution 6:

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.