Saturday, 5 April 2014

Closure- Real worl Problem of Syncronyse setTimeout within for loop

Before starting solution., Let discuss the problem. What exactly problem is all about and how we will resolve it

First look at the below given code:
function myFunction()
{
   for(var i=0;i<10;i++){
   setTimeout(function(){alert(i)},3000);
   }
}

//output:
//Predictable in case if for loop completes before 3000milisec.
//i.e Output would be 1o times 10.

Now suppose i want to print all possible values of the i, in alert. i.e. 0,1,2...9 what we will do??

Here closure comes in picture.

Closure:The function defined in the closure 'remembers' the environment in which it was created in. 

As definition you can see that a closure method remembers its value the environment it was create. So we will modify our code, so that it can synchronized for loop with setTmeout method.


function myFunction()
{
   //Closure example

   for(var i=0;i<10;i++){
   (function(i){ // here we have created an anonymous method.

      setTimeout(function(){alert(i)},3000);
   })(i); // It will self excute with the values of i

  }
}

//output:
//i.e Output would be 1,2,3....10

Here in above code we have added a closure anonymous method. It self invoked on each loop.