- 写出其输出情况
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(new Date, i);
}, 1000);
}
console.log(new Date, i);
- 用闭包解决for click
for (var i = 0; i < 5; i++) {
(function(i) { // j = i
setTimeout(function() {
console.log(new Date, i);
}, 1000);
})(i);
}
console.log(new Date, i);
- 用按值传递解决for click
var output1 = function (i) {
setTimeout(function() {
console.log(new Date, i);
}, 1000);
};
for (var i = 0; i < 5; i++) {
output1(i); // 这里传过去的 i 值被复制了
}
console.log(new Date, i);
- es6 promise实现逐秒输出0-5
const tasks = []; // 这里存放异步操作的 Promise
const output2 = (i) => new Promise((resolve) => {
setTimeout(() => {
console.log(new Date, i);
resolve();
}, 1000 * i);
});
// 生成全部的异步操作
for (var i = 0; i < 5; i++) {
tasks.push(output2(i));
}
// 异步操作完成之后,输出最后的 i
Promise.all(tasks).then(() => {
setTimeout(() => {
console.log(new Date, i);
}, 1000);
});
- es7 async await实现逐秒输出0-5
// 模拟其他语言中的 sleep,实际上可以是任何异步操作
const sleep = (timeountMS) => new Promise((resolve) => {
setTimeout(resolve, timeountMS);
});
(async () => { // 声明即执行的 async 函数表达式
for (var i = 0; i < 5; i++) {
await sleep(1000);
console.log(new Date, i);
}
await sleep(1000);
console.log(new Date, i);
})();
知乎原帖链接