zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Python中的memoryview
    Python常见陷阱
    特殊方法 之 len __repr__ __str__
    collections模块
    使用math中的hypot实现向量
    Ellipsis对象
    array
    标准库heapq的使用
    Mysql常用命令
    使用npm查看安装的包
  • 原文地址:https://www.cnblogs.com/haveadate/p/15394907.html
Copyright © 2011-2022 走看看