当 clearInterval() 不停止计时器时,如何停止计时器?
这段代码的目的是使一个数字从 0 向上直到它结束(例如,从 0...75% 开始动画)。但是当我调用 clearInterval() 时计时器不会停止:
<div id="foo"></div>
<div id="bar"></div>
animate("99%", $("#foo")); // doesnt stop
animate("75%", $("#bar")); // doesnt stop
function loop(clr, clr2, ele, rand, last, delay) {
clearInterval(clr);
clearInterval(clr2);
inloop(clr, clr2, ele, rand, last, delay);
if (rand >= last) {
clearInterval(clr);
clearInterval(clr2);
}
else {
clr2 = setTimeout(function () {
loop(clr, clr2, ele, rand, last, delay);
}, 2500);
}
}
function inloop(clr, clr2, ele, rand, last, delay) {
ele.html((rand += 1) + "%");
if (rand >= last) {
clearInterval(clr);
clearInterval(clr2);
}
else {
clr = setTimeout(function () {
inloop(clr, clr2, ele, rand, last, delay);
}, delay);
}
}
function animate(end, display) {
var clr = null;
var clr2 = null;
var ele = null;
var rand = 0; // initial number
var last = 99; // last number
var delay = 5; // inner loop delay
ele = display;
ele.html("0%");
var idx = end.indexOf("%");
if (idx >=0) {
end = end.substring(0,idx);
}
last = parseInt(end);
loop(clr, clr2, ele, rand, last, delay);
}