循环打印红绿黄

文章目录

  • 1 循环打印红绿黄
    • 1.1 用callback实现
    • 1.2 用Promise实现
    • 1.3 用async/await实现

1 循环打印红绿黄

  • 问题描述:红灯 3s 亮一次,绿灯 1s 亮一次,黄灯 2s 亮一次,如何让三个灯不断交替重复亮灯?
  • 这道题复杂的地方在于需要“交替重复”亮灯,而不是“亮完一次”就结束了。
  • 通过这个问题来对比几种异步编程方法。

1.1 用callback实现

function red() {
    console.log('red');
}

function green() {
    console.log('green');
}

function yellow() {
    console.log('yellow');
}

const task = (timer, light, callback) => {
    setTimeout(() => {
        if (light === 'red') {
            red();
        } else if (light === 'green') {
            green();
        } else if (light === 'yellow') {
            yellow();
        }
        callback();
    }, timer);
};

const step = () => {
    task(3000, 'red', () => {
        task(2000, 'green', () => {
            task(1000, yellow, step);
        })
    })
};
step();

1.2 用Promise实现

const task = (timer, light) => {
    new Promise((resolve, reject) => {
        setTimeout(() => {
            if (light === 'red') {
                red();
            } else if (light === 'green') {
                green();
            } else if (light === 'yellow') {
                yellow();
            }
            resolve();
        }, timer);
    })
};
const step = () => {
    task(3000, 'red')
        .then(() => task(2000, 'green'))
        .then(() => task(2100, 'yellow'))
        .then(step);
};
step();

1.3 用async/await实现

const taskRunner = async() => {
    await task(3000, 'red');
    await task(2000, 'green');
    await task(1000, 'yellow');
    taskRunner();
};
taskRunner();

你可能感兴趣的:(前端面试,javascript,前端)