Skip to content

Instantly share code, notes, and snippets.

@ifkas
Last active February 21, 2018 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ifkas/a91b26371909abe80fef4e7d98c51750 to your computer and use it in GitHub Desktop.
Save ifkas/a91b26371909abe80fef4e7d98c51750 to your computer and use it in GitHub Desktop.
Shared variable - JavaScript closure
function foo() {
let num = 0;
setTimeout(function(){
console.log("I have " + num++ + " apple");
},100);
setTimeout(function(){
console.log("I have " + num++ + " apple");
},300);
}
foo();
// > I have 0 apple
// > I have 1 apple
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment