Skip to content

Instantly share code, notes, and snippets.

@llimacruz
Created March 26, 2017 15:10
Show Gist options
  • Save llimacruz/dc661bb640b14075ce0406a650a7f0cf to your computer and use it in GitHub Desktop.
Save llimacruz/dc661bb640b14075ce0406a650a7f0cf to your computer and use it in GitHub Desktop.
Assinc for in js
'use strict';
// does not work
for (var i = 1; i <5; i++) {
setTimeout(function() {
console.log('i: ' + i);
}, i * 1000);
}
// work
for (var i = 1; i <5; i++) {
let j = i;
setTimeout(function() {
console.log('i: ' + i + ' j: ' + j);
}, i * 1000);
}
// work
for (var i = 1; i <5; i++) {
(function(i) {
setTimeout(function() {
console.log('i: ' + i);
}, i * 1000);
})(i);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment