ThElitEyeS
ThElitEyeS

Reputation: 647

Javascript setInterval clearing itself?

I'm wondering if there's a way to make setInterval clear itself.

Something like this:

setInterval(function () {
    alert(1);
    clearInterval(this);
}, 2000);

I want it to keep checking thing if it's finished it will stop.

Upvotes: 21

Views: 16106

Answers (2)

user1106995
user1106995

Reputation: 800

Try this way:

var myInterval = setInterval(function () {
    alert(1);
    clearInterval(myInterval);
}, 2000);

Alternative way is using setTimeout() if you know it is just one time call.

Upvotes: 41

Corbin
Corbin

Reputation: 33457

(​function() {
    var runs = 3;
    var i = setInterval(function() {
        console.log("Number " + runs);                         
        --runs;
        if (runs == 0) {
             clearInterval(i);
        }    
    }, 1000);
}());​

jsfiddle

Upvotes: 9

Related Questions