
获得徽章 0
- js实现一个红绿灯的功能:红灯 3s 亮一次,绿灯 1s 亮一次,黄灯 2s 亮一次
解题思路:promise+setTimeout+递归
function red() {
console.log('red')
}
function green() {
console.log('green')
}
function yellow() {
console.log('yellow')
}
// 用 promise 实现
let task = (timer, light) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (light === 'red') {
red()
}
if (light === 'green') {
green()
}
if (light === 'yellow') {
yellow()
}
resolve()
}, timer)
})
}
let step = async (params) => {
await task(3000, 'red')
await task(2000, 'yellow')
await task(1000, 'green')
step()
}
step()展开2点赞