我正在编写一个脚本,其中包含一个需要每 10 分钟调用一次的函数。此外,为了通知用户在重新加载函数之前还剩下多少时间(通过 AJAX,但现在这无关紧要),我放了一个小回归计时器。
这是主要结构:
$(document).ready(function () {
// Test's function
function loadDate() {
var myDate = new Date();
$("#dateload").html(myDate);
};
// Startup Variables
countermin = 10; // 10 minutes
countersec = 60;
minpass = 0;
secpass = 0
// Showing info before timer.
$("#reloadtime").html("Function will be reloaded in " + countermin + "m<b>" + (60 - countersec) + "</b>s<br/>(countersec's value: " + countersec + " - secpass' value: " + secpass + ")");
$("#timescalled").text("The date function has been called " + minpass + " times after page's load.");
loadDate();
// FIRST setInterval
// It's our timer.
intvl1 = setInterval(function () {
if (countersec++ == 60) {
countermin--;
countersec = 1;
}
if (countermin < 0) {
countermin = 9;
countersec = 1;
secpass = 0;
}
secpass++;
$("#reloadtime").html("Function will be reloaded in " + countermin + "m<b>" + (60 - countersec) + "</b>s<br/>(countersec's value: " + countersec + " - secpass' value: " + secpass + ")");
}, 1000);
// SECOND setInterval
// Counting 10 minutes to execute the function again (and again...).
intvl2 = setInterval(function () {
minpass++;
$("#minpass").text("The date function has been called " + minpass + " times after page's load.");
loadDate();
}, 600000);
});
我的问题是:两个计时器都不同步。intvl2
正在执行函数并在计时器( )到达 0 之前返回。intvl1
误差约为 20 秒,每 10 分钟增加一次。
如果您与开始时打印的时间进行比较,在与您的 PC 时钟进行比较时,您可以看到执行大约 6、7 分钟时的时间差异。
我怎样才能让它们同步?
你可以检查这个小提琴。