1. callback方法
function red() {
console.log('red');
}
function green() {
console.log('green');
}
function yellow() {
console.log('yellow');
}
function lightToggle(fn, timer, callback) {
setTimeout(() => {
if (fn === 'red') {
red()
}
else if (fn === 'green') {
green()
}
else if (fn === 'yellow') {
yellow()
}
callback()
}, timer)
}
function a() {
lightToggle("red", 3000, b)
}
function b() {
lightToggle("yellow", 2000, c)
}
function c() {
lightToggle("green", 1000, a)
}
a()
2. promise方法
// 使用promise实现
function task(light, delay) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (light === 'red') {
red()
}
else if (light === 'green') {
green()
}
else if (light === 'yellow') {
yellow()
}
resolve()
}, delay)
})
}
async function task_all() {
await task('red', 3000)
await task('yellow', 2000)
await task('green', 1000)
task_all()
}
task_all()
// const step = () => {
// task('red', 3000)
// .then(() => task('yellow', 2000))
// .then(() => task('green', 1000))
// .then(step)
// }
// step()