SetInterval in for loop in Javascript

Normally we used interval with normal way.

var i  = 0;
var id = setInterval(function(){
    if(i == 10){
        clearInterval(id)
    } else {
        i++;
        console.log(i);
    }
}, 1000)

[vc_text_separator title=”Now”]

We need to use this with for loop but there we will use setTimeout instead of setInterval.

for(var i=0; i<10; i++){
    (function(i){
        setTimeout(function(){
            console.log(i)
        },1000*i);
    })(i)
}

Leave a Reply

Your email address will not be published. Required fields are marked *