Simulated traffic light

Analog traffic lights: red 3s, green 2s, yellow 1s, and so on

The author thought about a, simple and rough, is written like this:

Function lights(){console.log(' light '); SetTimeout (()=>{console.log(' green '); SetTimeout (()=>{console.log(' yellow light '); setTimeout(()=>{ lights() },1000) },2000) },3000) } lights()Copy the code

Later, the interviewer asked me if THERE was another way to implement it, like Promise. He said that I would lose frames in this way (put a question mark here, add why will lose frames below) a face meng force, do not quite understand his meaning, down I think about it carefully, add. Promise chain call:

Function lights(){promise.resolve (). Then ()=>{return new Promise((res,rej)=>{console.log(' console.log '); SetTimeout () = > {resolve ()}, 3000)})}). Then (() = > {return new Promise ((res, rej) = > {the console. The log (' green '); setTimeout(()=>{ resolve(); }, 2000)})}). Then (() = > {return new Promise ((res, rej) = > {the console. The log (" yellow "); setTimeout(()=>{ lights() },1000) }) }) }Copy the code

The interviewer can also said a async await the way, the method reference to the attached link online: www.cnblogs.com/yanjianjian.

class LightFn{
    async run(){
        while(true){
            console.log('this is green 3000');
            await this.sleep(3000);
            console.log('this is yellow 1000');
            await this.sleep(1000);
            console.log('this is red 2000');
            await this.sleep(2000);            
        }    
    }
    sleep(duration){
        return new Promise((resolve, reject)=>{
            setTimeout(resolve ,duration);
        })
    }
}

let a = new LightFn();
a.run();
Copy the code

PS: About the disadvantages of setInterVal, there is time to sort out and learn.