Skip to content

Instantly share code, notes, and snippets.

@gotraveltoworld
Created March 12, 2019 16:22
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 gotraveltoworld/8cd972ca2cf90d51d3b754f1854139d9 to your computer and use it in GitHub Desktop.
Save gotraveltoworld/8cd972ca2cf90d51d3b754f1854139d9 to your computer and use it in GitHub Desktop.
To practice the JS setTimeout: 測試迴圈內 "i" 的結果,這題要研究var 和 let 之間的關係(重點在全域綁定和區域綁定), let vs var
// 測試迴圈內 "i" 的結果,這題要重新研究var 和 let 之間的關係(重點在全域綁定和區域綁定)
for (var i = 0; i < 10; i ++) {
setTimeout(function() {
console.log(i);
}, 10);
}
for (let i = 0; i < 10; i ++) {
setTimeout(function() {
console.log(i);
}, 10);
}
// ES5 要正確的寫法:(利用function scope)
// for (var i = 0; i < 10; i++) {
// (function (j) {
// setTimeout(function () {
// console.log('這執行第' + j + '次');
// }, 10);
// })(i);
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment