-2
 for ( var d = 0; d < 3; d++ )
        (function(d)
        {
            setTimeout(
                    function()
                    {
                        console.log( "Value of d: ", d );
                        console.log( d == d, "Check the value of d." );
                    }, d * 200);
        })(d);

How the time parameter(d) is working? setTimeout inside of for loop. Confusion to use SetTimeout within for loop.

Mohammad Faizan khan
  • 1,213
  • 3
  • 17
  • 32
  • the core concept is the use of a closure variable in a loop - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake – Arun P Johny Feb 27 '14 at 06:17
  • 1
    http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Arun P Johny Feb 27 '14 at 06:18
  • and [IIFE](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) – Arun P Johny Feb 27 '14 at 06:18

2 Answers2

0

probably you should understand (function(arg){})(d) defines an anonymous function and immediataly call it with an argument d

D Blacksmith
  • 123
  • 2
  • 6
0

The code seems to work fine.

But if you are rather trying to understand it, you can end up picking up an import trade of JS.. Closures

So first run it like this

for ( var d = 0; d < 3; d++ )       
      setTimeout(function() {
                    console.log( "Value of d: ", d );
                    console.log( d == d, "Check the value of d." );
                }, d * 200);

The output :

Value of d:  3 
true "Check the value of d." 
Value of d:  3 
true "Check the value of d." 
Value of d:  3 
true "Check the value of d." 

Did you notice the non incremented value of d? This is because the value of d becomes 3 before any of the setTimeout function is actually executed. So what you need are three copies of d with the value 1,2,3.

This can be achieved with executing an immediate function & saving the value of d at the time of defining the setTimeout function itself. What we essentially do is wrap each call inside a scope where d is accessible later (after setTimeout functions kick off).

Hence your code:

for ( var d = 0; d < 3; d++ ) (function(d) {
            setTimeout(function() {
                        console.log( "Value of d: ", d );
                        console.log( d == d, "Check the value of d." );
                    }, d * 200);
        })(d);

produces output :

Value of d:  0
true "Check the value of d."
Value of d:  1
true "Check the value of d."
Value of d:  2
true "Check the value of d." 
loxxy
  • 12,990
  • 2
  • 25
  • 56