Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a javascript setTimeout loop

Tags:

jquery

I have this loop that works okay:

function countdown(counter) {
    x = counter;
    if (x > 0) {
        x--;
        alert(x + "/5");
        if (x > 0) {
            setTimeout(function () {
                countdown(x);
            }, 500);
        }
    }
};

countdown(6);

But I'd like to be able to kill it, and start it again by pressing a button. I'd like to restart the loop, regardless of what number it's on when I press the button.

I've got nowhere over the last few hours.

Here's a jsfiddle: http://jsfiddle.net/4vtPH/4/

like image 634
Starkers Avatar asked May 14 '26 21:05

Starkers


1 Answers

You can use clearTimeout (documentation)

var timeout;
function countdown(counter) {
    x = counter;
    if (x > 0) {
        x--;
        alert(x + "/5");
        if (x > 0) {
            timeout = setTimeout(function () {
                countdown(x);
            }, 2000);
        }
    }
};
$('input').click(function() {
    clearTimeout(timeout);
    countdown(6);
});
countdown(6);

Fiddle

like image 61
Dan-Nolan Avatar answered May 17 '26 10:05

Dan-Nolan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!