我正在尝试创建一个回调我的Web API以收集新的竞赛数据,我已经创建了一个setInterval
并对其进行了测试,看它是否按照我的预期登录到控制台,但是控制台记录两次的原因。我不明白为什么。
我想删除if语句中的console.log()
并将其替换为对服务器的调用,但如果它记录两次,我将收到两倍的信息。
var TimeOutID = '';
var TenRaces = 0;
var StartThis = function () {
console.log("Starting run");
//Simulate counting down to next race
TimeOut = new Date().getTime() + 5000;
$('#next').countdown(TimeOut, function (event) {
$(this).html(event.strftime('%H:%M:%S'));
if(event.elapsed) {
//once the countdown timer has elapsed fetch data
console.log("Race: " + TenRaces); // <-- this one is logged twice
}
});
//loop ten races simulating ten different times data is needed
TenRaces++;
if (TenRaces > 10) {
clearInterval(TimeOutID);
}
};
TimeOutID = setInterval(StartThis, 6000);
为什么console.log()
正在运行并记录两次?
答案 0 :(得分:0)
根据文档,经过时间模式是故意设计的,以便在倒计时结束后继续。因此我认为它在TenRaces var迭代之前循环两次。如果你没有迭代那个var,它会永远记录下来。
在finish.countdown事件上执行日志/获取数据,这只会在倒计时结束时触发一次。参见文档:
E.g。
$('div#clock').countdown(finalDate)
.on('finish.countdown', callback);