每 30 秒运行一个函数 javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21638574/
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-10-27 21:23:38  来源:igfitidea点击:

Run a function every 30 seconds javascript

javascriptfunctiontimer

提问by user2580555

I am trying to run a function every 30 seconds but setInterval waits 30 seconds then runs it repeatedly. So if there are any other methods of going about this. (Without 3rd party plugins)

我试图每 30 秒运行一次函数,但 setInterval 等待 30 秒然后重复运行它。因此,如果有任何其他方法可以解决此问题。(没有第 3 方插件)

Any help would be appreciated

任何帮助,将不胜感激

回答by Gary Carlyle Cook

Based on the answer from "Schechter" but fixed to run on the first page load and then runs every 30 secs.

基于“Schechter”的回答,但固定在第一页加载时运行,然后每 30 秒运行一次。

function myFunction(){
    console.log('myFunction Called')
}

myFunction();

setInterval(function(){
    myFunction()
}, 30000)

回答by Schechter

function foo(){
    console.log('function is being called')
}

setInterval(function(){
    foo()}, 30000)

The second argument in setInterval is the time delay in milliseconds, so use 30000 for 30 seconds, not 30.

setInterval 中的第二个参数是以毫秒为单位的时间延迟,因此使用 30000 表示 30 秒,而不是 30。

回答by Matt

function blah(){}

blah();
setInterval(blah,30000);