有没有办法让一些 JS 代码每60秒执行一次?我认为 while循环是可行的,但是有更简洁的解决方案吗?欢迎使用 JQuery,一如既往。
while
Using setInterval:
setInterval(function() { // your code goes here... }, 60 * 1000); // 60 * 1000 milsec
The function returns an id you can clear your interval with clearInterval:
var timerID = setInterval(function() { // your code goes here... }, 60 * 1000); clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.
A "sister" function is setTimeout/clearTimeout look them up.
If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:
function fn60sec() { // runs every 60 sec and runs on init. } fn60sec(); setInterval(fn60sec, 60*1000);
You could use setInterval for this.
setInterval
<script type="text/javascript"> function myFunction () { console.log('Executed!'); } var interval = setInterval(function () { myFunction(); }, 60000); </script>
Disable the timer by setting clearInterval(interval).
clearInterval(interval)
See this Fiddle: http://jsfiddle.net/p6NJt/2/
to call a function on exactly the start of every minute
let date = new Date(); let sec = date.getSeconds(); setTimeout(()=>{ setInterval(()=>{ // do something }, 60 * 1000); }, (60 - sec) * 1000);