90

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

4

3 回答 3

161

使用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);
于 2012-11-09T08:22:24.943 回答
12

你可以用setInterval这个。

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

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

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

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

于 2012-11-09T08:31:31.053 回答
0

在每分钟开始时调用一个函数

let date = new Date();
let sec = date.getSeconds();
setTimeout(()=>{
  setInterval(()=>{
    // do something
  }, 60 * 1000);
}, (60 - sec) * 1000);
于 2022-02-07T13:30:42.557 回答