简体   繁体   中英

clearInterval does not work

I'm trying to create a simple countdown timer. It counts down from the number entered.

However, I'm trying to clear the interval when the counter gets to 0 . At the moment it seems to acknowledge the if statement , but not clearInterval() .

http://jsfiddle.net/tmyie/cf3Hd/

$('.click').click(function () {
    $('input').empty();
    var rawAmount = $('input').val();
    var cleanAmount = parseInt(rawAmount) + 1;

    var timer = function () {

        cleanAmount--;

        if (cleanAmount == 0) {

            clearInterval(timer);
        }
        $('p').text(cleanAmount);
    };

    setInterval(timer, 500);

})

You're not saving the return value of the call to setInterval , which is the value that needs to be passed to clearInterval . Passing the timer handler does no good.

var timer, timerHandler = function () {

    cleanAmount--;

    if (cleanAmount == 0) {

        clearInterval(timer);
    }
    $('p').text(cleanAmount);
};

timer = setInterval(timerHandler, 500);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM