JS 模仿红绿灯(控制台)

时间:2021-10-11
本文章向大家介绍JS 模仿红绿灯(控制台),主要包括JS 模仿红绿灯(控制台)使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

async/await

function createLight(type, delay) {
    return new Promise((resolve, reject) => {
        console.log(type);
        setTimeout(() => resolve(), delay * 1000);
    });
}

const lights = [
    createLight.bind(null, '红灯', 4),
    createLight.bind(null, '黄灯', 2),
    createLight.bind(null, '绿灯', 4)
];

async function start() {
    while(true) {
        for (const light of lights) {
            await light();
        }
    }
}

start();

for...await...of

function createLight(type, delay) {
    return new Promise((resolve, reject) => {
        console.log(type);
        setTimeout(() => resolve(type), delay * 1000);
    });
}

async function* lightGenerator() {
    const lights = [
        createLight.bind(null, '红灯', 4),
        createLight.bind(null, '黄灯', 2),
        createLight.bind(null, '绿灯', 4)
    ];

    for (const light of lights) {
        yield light();
    }
}

async function start() {
    while(true) {
        for await (const type of lightGenerator()) {
            // console.log(type);
        }
    }
}

start();

展示

codepen

原文地址:https://www.cnblogs.com/haveadate/p/15394907.html