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.