Skip to content

Instantly share code, notes, and snippets.

@ben-ng ben-ng/gist:9500587
Created Mar 12, 2014

Embed
What would you like to do?
closure/asynchrony/hoisting
// 1 (closures/asyncrony)
function sleepsort (input) {
for(var i=0; i<input.length; i++) {
setTimeout(function () {
console.log(i);
}, i * 1000);
console.log('iterated');
}
};
sleepsort([2, 1, 3])
// show that "iterated" is printed before any of the array elements are
// 2
function sleepsort (input) {
for(var i=0; i<input.length; i++) {
var j = i; // explain why this doesn't work (hoisting)
setTimeout(function () {
console.log(j);
}, j * 1000);
}
};
// 3 explain why this works (functions create scope)
function sleepsort (input) {
for(var i=0; i<input.length; i++) {
(function (j) {
setTimeout(function () {
console.log(j);
}, j * 1000);
})(i);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.