0

What is the purpose of putting addMarketMethod() within an anonymous function in this example?

function drop() {
  for (var i =0; i < markerArray.length; i++) {
    setTimeout(function() {
      addMarkerMethod();
    }, i * 200);
  }
}

Instinctively, I would have written this as:

function drop() {
  for (var i =0; i < markerArray.length; i++) {
    setTimeout(addMarkerMethod(), i * 200);
  }
}

Ran into this example while reading up on the Google Maps API for pset 8. Source: https://developers.google.com/maps/documentation/javascript/markers.

2
  • 1
    It doesn't look the same to me. In your first code block, the first parameter of setTimeout() is a function. In your second code block, the first parameter of setTimeout() is a function call rather than a function ... – Peter Pesch Sep 24 '18 at 5:10
  • It's the value returned by the function call. Otherwise, correct observation. – Blauelf Sep 24 '18 at 16:02
0

Your second example probably meant to be

setTimeout(addMarkerMethod, i * 200);

without the pair of parentheses. The event loop will cause your function to be called once it gets enqueued.

In that case, no difference. The benefit of the first version might be that you can do more complex things. Chain multiple function calls for example. And I think that's what it's used for here, assuming you don't just want to call that function, but do more.

Also, another kind of function is frequently used in loops: IIFEs (Immediately Invoked Function Expressions). JavaScript before ECMAScript2015 AKA ECMAScript6 AKA ES6 (ES6 is supported on most current browsers) did not know block-scope variables, so code like

for (var i = 0; i < 10; i++) {
  window.setTimeout(function(){
    console.log("Counter is " + i);
  }, i * 200);
}

is printing Counter is 10 ten times. You created 10 different functions, but they all use the i defined in the outer function, and after that loop, that has the value of 10.

The ES6 fix for that is to use let rather than var in the for loop, this binds a new variable for each iteration, even though they all go by the same name.

The ES5 fix was to use those IIFEs I mentioned, create a function expression and immediately execute it to create a new scope. My example then would look like

for (var i = 0; i < 10; i++) {
  window.setTimeout(function(counter){ // create the outer function
    return function(){
      console.log("Counter is " + counter);
    }
  }(i), i * 200); // and call it immediately
}

The outer function is called, returning the inner function. Function parameter counter (by the call set to the current value of i) exists in a scope that's unique to the iteration, and not shared, and is accessible to the inner function. If you see an IIFE with var and assignments rather than function parameters, that's the same, in ES5 these live in the same scope.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .