Skip to content

Instantly share code, notes, and snippets.

@hthuong09
Created September 28, 2016 06:11
Show Gist options
  • Save hthuong09/173ff8238c02cb3eca53b79862f18cef to your computer and use it in GitHub Desktop.
Save hthuong09/173ff8238c02cb3eca53b79862f18cef to your computer and use it in GitHub Desktop.
Pass argument to setTimeout inside loop
/*
Syntax
fun.bind(thisArg[, arg1[, arg2[, ...]]])
Parameters
thisArg
The value to be passed as the this parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the new operator.
Passed undefined = use original this
arg1, arg2, ...
Arguments to prepend to arguments provided to the bound function when invoking the target function.
Return value
A copy of the given function with the specified this value and initial arguments.
*/
for(var i = 0; i < 10; i++) {
setTimeout(function(i){
console.log(i);
}.bind(undefined, i), 1000 * i);
}
for(var i = 0; i < 10; i++) {
setTimeout(function(i){
return function() { console.log(i); };
}(i), 1000 * i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment