本文翻译自:What's the easiest way to call a function every 5 seconds in jQuery? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
JQuery, how to call a function every 5 seconds. jQuery,如何每5秒调用一次函数。
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. 如果可能的话,我宁愿不安装其他任何第三方插件。
参考:https://stackoom.com/question/96kt/在jQuery中每-秒调用一次函数的最简单方法是什么-重复
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);
You don't need jquery for this, in plain javascript, the following will work! 您不需要为此使用纯JavaScript的jquery,以下方法将起作用!
window.setInterval(function(){
/// call your function here
}, 5000);
To stop the loop you can use 要停止循环,您可以使用
clearInterval()
you could register an interval on the page using setInterval, ie: 您可以使用setInterval在页面上注册间隔,即:
setInterval(function(){
//code goes here that will be run every 5 seconds.
}, 5000);
Both setInterval
and setTimeout
can work for you (
as @Doug Neiner and @John Boker wrote
both now point to setInterval
). setInterval
和setTimeout
都可以为您工作(
正如@Doug Neiner和@John Boker所写的
两者都指向setInterval
)。
See here for some more explanation about both to see which suites you most and how to stop each of them. 有关更多信息,请参见此处 ,以了解最适合您的套件以及如何停止每个套件。
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 上面提到的函数无论是否在先前的调用中完成都将执行,一旦执行完成,此函数将每隔x秒运行一次
// 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
}