-2

Simple question...

for (var i = 0; i < 5; i++) {            
   setTimeout(function () { alert(i) }, 3000);
}

how to alert 5 times with exact value of i.

It gives "5" only 5 times.

I need its result like 0 1 2 3 4

2 Answers2

2

With a closure that keeps the value of the variable constant within the new scope of the immediately invoked function

for (var i = 0; i < 5; i++) {            

   (function(j) {

       setTimeout(function () { alert(j) }, 3000);

   }(i));
}

The setTimout is asynchronous, so by the time it executes the loop has long since completed, and the value of i has been changed to 5, so you need to lock it in.

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You can use setInterval alternate to setTimeout

Try,

var xCnt = 0;
var xInterval = setInterval(function()
                              {
                                xCnt +=1;  
                                alert(xCnt);

                                  if(xCnt == 5)
                                    { 
                                       clearInterval(xInterval); 
                                    }
                              }, 3000);

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130