5

当 clearInterval() 不停止计时器时,如何停止计时器?

这段代码的目的是使一个数字从 0 向上直到它结束(例如,从 0...75% 开始动画)。但是当我调用 clearInterval() 时计时器不会停止:

http://jsfiddle.net/pwYEe/2/

<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);
}
4

1 回答 1

13

你使用clearTimeout()with setTimeout()

你不使用clearInterval()with setTimeout()clearInterval()setInterval().

您的代码中也存在结构性问题。您将 clr 和 clr2 作为参数传递,并期望它们的原始值被修改,而事实并非如此。

您可以通过将它们都放在一个对象中并像这样传递对象来解决这个问题:

animate("99%", $("#foo"));
//animate("75%", $("#bar"));

function loop(timers, ele, rand, last, delay) {
    clearTimeout(timers.clr);
    clearTimeout(timers.clr2);
    inloop(timers, ele, rand, last, delay);

    if (rand >= last) {
        clearTimeout(timers.clr);
        clearTimeout(timers.clr2);
    }
    else {
        timers.clr2 = setTimeout(function () {
            loop(timers, ele, rand, last, delay);
        }, 2500);
    }

}
function inloop(timers, ele, rand, last, delay) {
    ele.html((rand += 1) + "%");

    if (rand >= last) {
        clearTimeout(timers.clr);
        clearTimeout(timers.clr2);
    }
    else {
        timers.clr = setTimeout(function () {
            inloop(timers, ele, rand, last, delay);
        }, delay);
    }
}

function animate(end, display) {
    var timers = {clr: null, 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(timers, ele, rand, last, delay);
}
​

工作jsFiddle:http: //jsfiddle.net/jfriend00/PEqeY/

于 2012-05-17T00:33:19.840 回答