Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript setInterval clearing itself?

Tags:

javascript

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.

like image 937
ThElitEyeS Avatar asked Mar 17 '12 04:03

ThElitEyeS


2 Answers

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.

like image 125
user1106995 Avatar answered Sep 19 '22 05:09

user1106995


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

jsfiddle

like image 22
Corbin Avatar answered Sep 19 '22 05:09

Corbin