代码看起来像这样:
function startTimer(counter) {
var interval = setInterval(function () {
counter--;
$('#timer').html(counter);
// Display 'counter' wherever you want to display it.
if (counter == 0) {
clearInterval(interval);
$('#question').html("Time ended");
setTimeout(function () {
window.location.href = "/";
}, 5000);
return false;
}
}, 1000);
}
我想要做的是,当我多次调用此函数时,每次将计时器重置为30秒并终止所有过去的实例。目前,当我多次打电话时,它会混淆过去的情况。我做错了什么?
答案 0 :(得分:0)
您必须在函数外定义var间隔:
var interval;
function startTimer(counter) {
interval = setInterval(function () {
counter--;
$('#timer').html(counter);
// Display 'counter' wherever you want to display it.
if (counter == 0) {
clearInterval(interval);
$('#question').html("Time ended");
setTimeout(function () {
window.location.href = "/";
}, 5000);
return false;
}
}, 1000);
}