关键词: 闭包 异步 词法作用域 事件队列 es6 ....
(function print() { for (var i = 0; i < 5; i++) { setTimeout(() => console.log(i),i*1000) }})()// 上面的方法 每隔1s打印 5(function print() { for( let i = 0; i < 5; i++) { setTimeout(() => console.log(i), i*1000) }})()// 每隔一秒打印 0 1 2 3 4(function print() { for(var i = 0; i < 5; i++) { (function(i) { setTimeout(() => console.log(i), i*1000) })(i) }})()// 每隔一秒打印 0 1 2 3 4function print(i) { return new Promise((resolve, reject) => { setTimeout(() => resolve(i), i*1000) })}var arr = [];for (var i = 0; i < 5; i++) { arr.push(print(i))}for (var i = 0; i < 5; i++) { arr[i].then(data => console.log(data))}// 每隔一秒打印 0 1 2 3 4// promise是一个容器,里面包含着异步操作function print(i) { return new Promise(resolve => { setTimeout(() => resolve(i), 1000) })}async function main() { for(var i = 0; i < 5; i++) { var r = await print(i) console.log(r) }}