-
Notifications
You must be signed in to change notification settings - Fork 1
/
for setTimeout.html
69 lines (43 loc) · 1.2 KB
/
for setTimeout.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
</body>
<script type="text/javascript">
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(new Date, i);
}, 1000);
}
console.log(new Date, i);
const tasks = [];
for (var i = 0; i < 5; i++) { // 这里 i 的声明不能改成 let,如果要改该怎么做?
((j) => {
tasks.push(new Promise((resolve) => {
setTimeout(() => {
console.log(new Date, j);
resolve(); // 这里一定要 resolve,否则代码不会按预期 work
}, 1000 * j); // 定时器的超时时间逐步增加
}));
})(i);
}
Promise.all(tasks).then(() => {
setTimeout(() => {
console.log(new Date, i);
}, 1000); // 注意这里只需要把超时设置为 1 秒
});
// 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);
// })();
</script>
</html>