Skip to content

Instantly share code, notes, and snippets.

@limabeans
Last active August 27, 2016 02:29
Show Gist options
  • Save limabeans/5d64b29cc34dd0366152f0060e76d288 to your computer and use it in GitHub Desktop.
Save limabeans/5d64b29cc34dd0366152f0060e76d288 to your computer and use it in GitHub Desktop.
tricky callback situations
/*
* Prints 'here', first, then roughly less than 1000 ms later, prints a b c d.
* For each element in the array, a setTimeout callback is set up, but since there's a 1000 ms delay, that function isn't
* called yet. The forEach won't block on any of these callback setups, so it skips through and prints 'here' first.
*/
function ex1() {
var arr = ['a', 'b', 'c', 'd'];
arr.forEach(function(e) {
setTimeout(function() {
console.log(e);
}, 1000);
});
console.log('here');
}
/*
* Common mistake, will print out 10, 10 times after 1 second.
* This is because i was incremented all the way to 10 before any of the delayed functions ran.
*/
function ex2_1() {
for (var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
}
/*
* The solution is to force each delayed function to have their own function scope with their own i.
*/
function ex2_2() {
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, 1000);
})(i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment