可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
-
Calling a function every 60 seconds
9 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.
回答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()
回答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);
回答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);
回答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
}
回答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);
回答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.
回答7:
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)
<script>
var time = 3670;
window.setInterval(function(){
// 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) {
clearInterval(x);
document.getElementById(\"demo\").innerHTML = \"EXPIRED\";
}
time--;
}, 1000);
</script>