Skip to content

Instantly share code, notes, and snippets.

@happymishra
Last active August 13, 2020 10:59
Show Gist options
  • Save happymishra/54f940ba620ca1964cf2f6ebe8089413 to your computer and use it in GitHub Desktop.
Save happymishra/54f940ba620ca1964cf2f6ebe8089413 to your computer and use it in GitHub Desktop.
var a = [1, 2, 3, 4]
for (var ai = 0; ai < a.length; ai++) {
setTimeout(function(){
// By the time this code will be executed, all the iterations of
// for loop would have completed and value of ai would be 4
console.log("Value of 'ai': " + ai)
}, 1000)
}
// Here, window object will have variable or property ai with value 4
// which will be accessed by setTimeout callback function, when it will be executed
console.log(window)
/*
Output:
Value of 'ai': 4
Value of 'ai': 4
Value of 'ai': 4
Value of 'ai': 4
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment