Skip to content

Instantly share code, notes, and snippets.

@user24
Created September 7, 2011 19:33
Show Gist options
  • Save user24/1201490 to your computer and use it in GitHub Desktop.
Save user24/1201490 to your computer and use it in GitHub Desktop.
Various For Loop Patterns
var i=0;
// 01234
for(i=0 ; i<5 ; i++) {
console.log('standard for loop', i);
}
// 55555
for(i=0 ; i<5 ; i++) {
setTimeout(function() {
console.log('async loop', i);
}, 50);
}
// 01234
for(i=0 ; i<5 ; i++) {
(function(i) {
setTimeout(function() {
console.log('async loop with closure', i);
}, 50);
})(i);
}
// 55555
for(i=0 ; i<5 ; i++) {
var foo = i;
var cb = function() {
console.log('stored callback loop', foo);
};
setTimeout(function() {
cb();
}, 50);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment