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.
Solution 1:
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)
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:
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function everyTime() {
console.log('each 1 second...');
}
var myInterval = setInterval(everyTime, 1000);
call this line to stop the loop:
clearInterval(myInterval);
Solution 4:
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 5:
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
}