【问题标题】:JavaScript: get code to run every minuteJavaScript:让代码每分钟运行一次
【发布时间】:2012-11-09 08:21:17
【问题描述】:

有没有办法让一些 JS 代码每 60 秒执行一次?我认为while 循环可能是可能的,但有没有更简洁的解决方案?一如既往地欢迎 JQuery。

【问题讨论】:

标签: javascript jquery html


【解决方案1】:

使用setInterval

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

该函数返回一个 ID,您可以使用 clearInterval 清除间隔:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

“姐妹”函数是setTimeout/clearTimeout 查找它们。


如果你想在页面 init 上运行一个函数,然后在 60 秒后,120 秒后,...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

【讨论】:

  • +1 for 60 * 1000,但最好在外部定义函数而不是传递匿名函数。
  • 问题,但是:如果我这样说,代码会在页面加载时执行,还是会在加载后 60 秒发生?
  • @Bluefire 在初始化后运行 60 秒
【解决方案2】:

您可以为此使用setInterval

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

通过设置clearInterval(interval)禁用定时器。

看到这个小提琴:http://jsfiddle.net/p6NJt/2/

【讨论】:

    【解决方案3】:

    在每分钟开始时调用函数

    let date = new Date();
    let sec = date.getSeconds();
    setTimeout(()=>{
      setInterval(()=>{
        // do something
      }, 60 * 1000);
    }, (60 - sec) * 1000);
    

    【讨论】:

    • 如果重要的是在每分钟开始时继续执行任何中等长度的时间,值得注意的是 JS 的 setInterval 在精确的时间保持上不是很可靠,这可能会进一步漂移离一分钟开始的时间越长。
    猜你喜欢
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 2014-12-01
    • 2011-09-06
    • 2019-06-09
    • 2015-03-27
    相关资源
    最近更新 更多