Possible Duplicate:
Calling a function every 60 seconds
I want to Call a Javascript function every 5 seconds continuously. I have seen the setTimeOut event. Will it be working fine if I want it continuously?
Possible Duplicate:
Calling a function every 60 seconds
I want to Call a Javascript function every 5 seconds continuously. I have seen the setTimeOut event. Will it be working fine if I want it continuously?
You can use setInterval()
, the arguments are the same.
const interval = setInterval(function() {
// method to be executed;
}, 5000);
clearInterval(interval); // thanks @Luca D'Amico
Do a "recursive" setTimeout
of your function, and it will keep being executed every amount of time defined:
function yourFunction(){
// do whatever you like here
setTimeout(yourFunction, 5000);
}
yourFunction();
As best coding practices suggests, use setTimeout
instead of setInterval
.
function foo() {
// your function code here
setTimeout(foo, 5000);
}
foo();
Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout
function that will be later call the same function again.
For repeating an action in the future, there is the built in setInterval
function that you can use instead of setTimeout
.
It has a similar signature, so the transition from one to another is simple:
setInterval(function() {
// do stuff
}, duration);
Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/
Plus:
fade in / fade out
animation:hover
Tested and working!