promise/async/await实现sleep函数(手写系列)

426 阅读1分钟
async function sleep(time){
    await new Promise(resolve => {        
        setTimeout(() => {
            resolve()
        }, time)
    })
}

// 实现红绿灯往复循环
async function fun(){
    await sleep(3000).then(res => { console.log('3秒执行绿灯') })
    await sleep(2000).then(res => { console.log('2秒执行黄灯') })
    await sleep(1000).then(res => { console.log('1秒执行红灯') })
    fun()
}
fun()