Skip to content

Instantly share code, notes, and snippets.

@ben-ng
Created March 12, 2014 03:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ben-ng/9500587 to your computer and use it in GitHub Desktop.
Save ben-ng/9500587 to your computer and use it in GitHub Desktop.
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