Created
September 28, 2016 06:11
-
-
Save hthuong09/173ff8238c02cb3eca53b79862f18cef to your computer and use it in GitHub Desktop.
Pass argument to setTimeout inside loop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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