Fil*_*eca 0 javascript jquery setinterval
我正在编写一个脚本,其中包含需要每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);
});
Run Code Online (Sandbox Code Playgroud)
我的问题是:两个计时器都不同步.该intvl2正在执行的功能和定时器(前回去intvl1)到达0的误差大约是20秒,每次10分钟后增加.
如果你比较开始时打印的时间,执行大约6,7分钟,你可以看到与PC时钟相比的时间差异.
我怎样才能让它们同步?
你可以检查这个小提琴.
一种更简单的方法是使用单个计时器来完成这两件事,更新倒计时信息并触发事件.以下是一个例子:
var oneSecond = 1000;
var counter = 0;
var eventInterval = 5 * oneSecond;
var timesTriggered = 0;
setInterval(function () {
counter = (counter + oneSecond) % eventInterval;
$('.countdown').text((eventInterval - counter) / oneSecond);
if(counter == 0){
timesTriggered++;
$('.timesTriggered').text(timesTriggered);
}
}, oneSecond);
Run Code Online (Sandbox Code Playgroud)
工作小提琴:http://jsfiddle.net/TFDSU/3/