4
當clearInterval()不停止它時,如何停止計時器?Javascript setTimeout不停在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);
}
大聲笑。我只是以這個問題爲例,它使用clearInterval:http://stackoverflow.com/a/4424211/325727。讓我相信我在互聯網上閱讀的任何內容。現在看起來不錯http://jsfiddle.net/pwYEe/4/ –
更正 - 那jsFiddle仍然無法正常工作。達到99%後,再次從0重新開始。不知道爲什麼 –
@JK - 請描述jsFiddle應該做什麼? – jfriend00