How to kill a javascript setTimeout loop

jquery

Solution

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

Problem

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/

Original source