Preserving variables inside async calls called in a loop.

f you want to run asynchronous functions inside a loop, but still want to keep the index or other variables after a callback gets executed you can wrap your code in an IIFE (immediately-invoked function expression).

var arr = ['Hello', 'World', 'Javascript', 'Async', ':)'];
for( var i = 0; i < arr.length; i++) {
 (function(index){
   setTimeout(function(){

      console.log(arr[index]);
   }, 500);

 })(i);
}

Author: Dominic Bartl
More Information: http://benalman.com/news/2010/11/immediately-invoked-function-expression/
Tags: function async

comments powered by Disqus