是的,如果您使用setInterval
並帶有間隔如你所見,它最終會開始漂移。但是,您不必持續不斷地進行調查:您只需使用鏈接電話setTimeout
即可。每個人都按照時鐘檢查自己。有時超時會是59999,有時候會是59997等等,但是它總會和時鐘保持一致。
function everyMinuteOnTheMinute() {
setTimeout(function() {
var d = new Date();
console.log(d.getMinutes() + " (" + d.valueOf() % 1000 + ")");
// your "every minute" code goes here
everyMinuteOnTheMinute();
}, 60000 - Date.now() % 60000);
}
您可以通過添加回調變成一個一般效用:
function everyMinuteOnTheMinute(cb) {
setTimeout(function() {
cb();
everyMinuteOnTheMinute(cb);
}, 60000 - Date.now() % 60000);
}
然後當你有一些代碼,你需要運行在分每分鐘,只需要使用效用函數:
everyMinuteOnTheMinute(function() {
console.log("Whee, I'm happening every minute on the minute!");
});
[setInterval時間慢慢偏離保持準確]的可能重複(http://stackoverflow.com/questions/8173580/setinterval-timing-slowly-drive-away-from-staying-accurate) – Josh
pos sible重複的[如何在JavaScript中創建一個精確的計時器?](http://stackoverflow.com/q/29971898/1048572) – Bergi