我想知道如何在点击链接时停止javascript计时器,而不一定是启动链接的计时器。这是我的代码中包含计时器的部分:
function doMiningcoal() {
if (!timer_is_on) {
timer_is_on = true;
t = setInterval(function () {
timedCount2();
}, 100);
}
}
function timedCount2() {
document.getElementById('txt').value = d;
d = d - 1;
if (d <= -1) {
coalCount++;
xp = 15 + xp
var _message = "You have mined " + coalCount + " coal" + (((coalCount > 1) ? "s" : "") + "!") + " You have " + xp + " xp";
document.getElementById('message').innerHTML = _message;
var _coal = coalCount + " Coal"
document.getElementById('coal').innerHTML = _coal
startover2();
}
}
function startover2() {
d = 20;
clearTimeout(t);
timer_is_on=0;
doMiningcoal();
}
答案 0 :(得分:0)
是在函数外部初始化的t变量吗?如果没有,以下函数不能使用它,因为它只在第一个函数本地,并且你的startover2函数中的t不相同(它的另一个本地函数)
-edit -
哦,您需要使用clearInterval
,因为您使用了setInterval
。
-edit2- -edit3,删除1行 -
var t = 0;
var timer_is_on = 0;
function doMiningcoal() {
if (!timer_is_on) {
timer_is_on = true;
t = setInterval(function () {
timedCount2();
}, 100);
}
}
function timedCount2() {
document.getElementById('txt').value = d;
d = d - 1;
if (d <= -1) {
coalCount++;
xp = 15 + xp
var _message = "You have mined " + coalCount + " coal" + (((coalCount > 1) ? "s" : "") + "!") + " You have " + xp + " xp";
document.getElementById('message').innerHTML = _message;
var _coal = coalCount + " Coal"
document.getElementById('coal').innerHTML = _coal
startover2();
}
}
function startover2() {
d = 20;
clearInterval(t);
timer_is_on=0;
}