Javascript setTimeout没有在clearInterval()上停止

时间:2012-05-17 00:32:15

标签: javascript settimeout clearinterval

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

1 个答案:

答案 0 :(得分:11)

您将clearTimeout()setTimeout()一起使用。

您不会将clearInterval()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/