JQuery setTimeout inside for loop

Today I was amazed with a question asked by one of my IT friends. 

What’ll be the output of setTimeout function if I declare it inside the for loop like this.

 

  1. for(i=0;i<3;i++)
  2. {
  3.     console.log(i);
  4. }
  5.  

 

My answer was 

 

  1. 0
  2. 1
  3. 2
  4.  

 

But the answer was not correct as he challenged and I checked it too. The answer was ‘2’ only.

 

I tried to know why the output is so. I thought that this is because of threading it’ll be skipping the setTimeout function some time due to thread concept. But when I changed the condition to i<10000, but the output was same. Finally I’s not able to know the situation and problem.

 

At last I searched on forems, and I got my answer which is as follows:

The function argument to setTimeout is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i, which is 4.

Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:

 

  1. for (var i = 0; i < 3; i++) {
  2. (function (x) {
  3. setTimeout(function () { alert(x); }, 100);
  4. })(i);
  5. }

 

You might also check this Q/A on stackoverflow