# ❓实现一个 sleep 函数
比如 sleep(1000) 意味着等待 1000 毫秒,可从 Promise、Generator、Async/Await 等角度实现
// Promise
const sleep = timestamp =>
new Promise(resolve => setTimeout(resolve, timestamp))
sleep(1000).then(() => {
console.log('我已经等了1000毫秒了')
})
// async
async function stepAsync() {
await sleep(1000)
console.log('我已经等了1000毫秒了')
}
stepAsync()
// Generator
function* stepGenerator(timestamp) {
yield new Promise(resolve => setTimeout(resolve, timestamp))
}
stepGenerator(1000)
.next()
.value.then(() => console.log('我已经等了1000毫秒了'))
// es5
function stepES5(timestamp, fn) {
setTimeout(fn, timestamp)
}
stepES5(1000, function() {
console.log('我已经等了1000毫秒了')
})
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
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