JavaScript:每分钟运行一次代码


76

有没有办法使每60秒执行一些JS代码?我以为有可能使用while循环,但是有没有更整洁的解决方案?像往常一样欢迎JQuery。



setInterval(expression,timeout); 以一定的间隔运行代码/函数,并在它们之间超时。
2012年

Answers:


145

使用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);

4
为+1 60 * 1000,但在外部定义函数而不是传递匿名函数也是一个好主意。
阿迪

1
问题是:如果我这样说,代码将在页面加载时执行,还是在加载60秒后执行?
Bluefire

2
@Bluefire它在初始化后运行60秒
andlrc

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/

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.