Today, roommate interview front end post, shared the face, which has a programming problem: the red light three seconds once, the green light one second once, yellow light two seconds once, how to make the three lights constantly alternating repeat light?Copy the code

When it comes to time, we should use the setTimeout method. We can tell the program to print red light after three seconds, green light after one second, and yellow light after two seconds.

    const red = () = > {
        setTimeout(() = > {
            console.log('red');
        },3000)}const green = () = > {
        setTimeout(() = > {
            console.log('green');
        },1000)}const yellow = () = > {
        setTimeout(() = > {
            console.log('yellow');
        },2000)
    }
    red();
    green();
    yellow();
Copy the code

Instead of printing red after 3 seconds, green after 1 second, and yellow after 2 seconds, you can directly execute these three methods. This is because setTimeout calls callbacks asynchronously. When the setTimeout method is executed, the callback is placed in an event queue, and the main thread continues to execute the following code.

Is there any way to wait for asynchronous execution to finish before executing the next code? Async/Await = Async/Await

let time = null;
const red = () = > {
  const now = Date.now();
  console.log('red'.Math.floor((now - time)/1000));
  time = Date.now();
}
const yellow = () = > {
  const now = Date.now();
  console.log('yellow'.Math.floor((now - time)/1000));
  time = Date.now();
}
const green = () = > {
  const now = Date.now();
  console.log('green'.Math.floor((now - time)/1000));
  time = Date.now();
}
const light = (time, callback) = > {
  return new Promise((res, rej) = > {
    const timer = setTimeout(() = >{ callback(); res(timer); }, time); })}const stepByStep = async() = > {const timer1 = await light(3000, red);
  const timer2 = await light(1000, green);
  const timer3 = await light(2000, yellow);
  clearTimeout(timer1);
  clearTimeout(timer2);
  clearTimeout(timer3);
}
time = Date.now();
stepByStep();
Copy the code

In the light method, you return an instance of a Promise that changes its state to complete only when the setTimeout callback executes, so you can take advantage of the nature of await: force the Promise to complete before continuing with the rest of the code.

And finally, how do you cycle them to alternate lights?

const stepByStep = async() = > {const timer1 = await light(3000, red);
  const timer2 = await light(1000, green);
  const timer3 = await light(2000, yellow);
  clearTimeout(timer1);
  clearTimeout(timer2);
  clearTimeout(timer3); StepByStep (); }Copy the code