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 fi开发者_如何学Pythonne 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:
- has nice
fade in / fade out
animation - will pause on
:hover
- will prevent running multiple actions (finish run animation before starting second)
- will prevent going broken when in the tab ( browser stops scripts in the tabs)
Tested and working!
精彩评论