Starkers
Starkers

Reputation: 10541

How to kill a javascript setTimeout loop

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/

Upvotes: 9

Views: 18828

Answers (4)

Marcel Gwerder
Marcel Gwerder

Reputation: 8520

How about using an interval for a countdown? Here is an alternative solution (DEMO):

function Countdown(counter) {
    this.interval = 0;
    this.x = counter;
    console.log(this.x + "/"+counter);
    this.start = function() {
        var self = this;
        this.interval = setInterval(function () {
            self.x--;
            console.log(self.x + "/"+counter);
            if(self.x == 0) self.stop();
        }, 2000);
    };

    this.stop = function() {
        clearInterval(this.interval);  
    };
};

var c = new Countdown(7);
c.start();

var c2 = new Countdown(4);

c2.start();

Upvotes: 0

Dan-Nolan
Dan-Nolan

Reputation: 6657

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

Upvotes: 16

marteljn
marteljn

Reputation: 6516

First you need to assign your setTimeout to a variable.

var timeout = setTimeout(..

Then when needed you can use clearTimeout(timeout). Make sure your timeout variable is scoped in a way that it can be accessed anywhere you need to access it.

Upvotes: 0

DaoWen
DaoWen

Reputation: 33019

You should really look at the documentation for setTimeout.

It returns a timeout id that you can use with clearTimeout to reset.

Upvotes: 0

Related Questions