每 5 秒连续调用一次 Javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7188145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:15:43  来源:igfitidea点击:

Call a Javascript function every 5 seconds continuously

javascriptdom-events

提问by deepmoteria

Possible Duplicate:
Calling a function every 60 seconds

可能的重复:
每 60 秒调用一次函数

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?

我想每 5 秒连续调用一次 Javascript 函数。我见过 setTimeOut 事件。如果我想要它连续工作,它会正常工作吗?

回答by Anantha Sharma

You can use setInterval(), the arguments are the same.

您可以使用setInterval(),参数是相同的。

const interval = setInterval(function() {
   // method to be executed;
 }, 5000);

clearInterval(interval); // thanks @Luca D'Amico

回答by Shef

Do a "recursive" setTimeoutof your function, and it will keep being executed every amount of time defined:

setTimeout对您的函数进行“递归” ,它将在定义的每个时间段内继续执行:

function yourFunction(){
    // do whatever you like here

    setTimeout(yourFunction, 5000);
}

yourFunction();

回答by Jose Faeti

As best coding practicessuggests, use setTimeoutinstead of setInterval.

正如最佳编码实践所建议的那样,使用setTimeout而不是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 setTimeoutfunction that will be later call the same function again.

请注意,这不是递归函数。该函数在结束之前不会调用自身,而是调用一个setTimeout稍后将再次调用相同函数的函数。

回答by gion_13

For repeating an action in the future, there is the built in setIntervalfunction that you can use instead of setTimeout.
It has a similar signature, so the transition from one to another is simple:

为了将来重复操作setInterval,您可以使用内置函数代替setTimeout
它有一个类似的签名,所以从一个到另一个的转换很简单:

setInterval(function() {
    // do stuff
}, duration);

回答by Iladarsda

Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/

这里很好的工作示例:http: //jsfiddle.net/MrTest/t4NXD/62/

Plus:

加:

  • has nice fade in / fade outanimation
  • 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)
  • 有很好的fade in / fade out动画
  • 将暂停 :hover
  • 将阻止运行多个动作(在开始第二个之前完成运行动画)
  • 将防止在选项卡中损坏(浏览器停止选项卡中的脚本)

Tested and working!

测试和工作!