Created
March 12, 2014 03:55
-
-
Save ben-ng/9500587 to your computer and use it in GitHub Desktop.
closure/asynchrony/hoisting
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
// 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