Javascript倒计时定时器w/Bootstrap模式暂停



请参阅下面的代码,我正试图让倒计时计时器在显示bs.modal时暂停,并在隐藏该模式后再次恢复。如果打开然后关闭模态,这将非常有效,但如果您再次尝试重新打开模态,计时器将继续。我可能遗漏了一些显而易见的东西,但在JS方面并不是最好的。

(function countdown(remaining) {
if(remaining === 0) {
location.reload(true);
}
document.getElementById('countdown').innerHTML = remaining;
$(document).on('shown.bs.modal', function(e) {
console.log("modal triggered");
clearTimeout(timeout);
});
$(document).on('hide.bs.modal', function(e) {
console.log("modal closed");

countdown(remaining - 1);
});
timeout = setTimeout(function(){
if(remaining != 0) {
countdown(remaining - 1);
}
}, 1000);
})(300);

现有代码的问题似乎是一个定时问题,导致同时设置多个超时,其中一些超时永远无法清除,因为它们的id丢失了。当您为每次迭代设置新的超时时,很容易陷入这种情况。所以,正如我提到的,setInterval((是一个更好的选择。下面是使用setInterval((的解决方案。还要注意,它的编写是为了确保在覆盖其id之前清除任何现有间隔(在函数clearAndSetInterval中(

(function (remaining) {
var interval;
var clearAndSetInterval = function () {
clearInterval(interval);
interval = setInterval(function (){
if (remaining <= 0) {
clearInterval(interval);
location.reload(true);
}
document.getElementById('countdown').innerHTML = remaining;
remaining = remaining - 1;
}, 1000);
};
$(document).on('shown.bs.modal', function(e) {
clearInterval(interval);
});
$(document).on('hide.bs.modal', function (e) {
clearAndSetInterval();
});
clearAndSetInterval();
})(300);

最新更新