How to implement traffic lights in javascript: 1. Use setTimeout and recursion to change colors cyclically; 2. Use Promise and write the next color change in then; 3. Use async await and while to implement traffic lights Effect.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.
How to implement traffic lights in javascript?
JavaScript to implement traffic lights
Use setTimeout, Promise, and async await in three ways to implement the traffic light code: red light for 2 seconds, yellow light for 1 second, green light for 3 seconds seconds, looping through to change colors. The method of changing the color is simply to print out the color.
setTimeout implementation
Using setTimeout is the most basic way to implement it. The code is as follows, using recursion to change colors in a loop.
function changeColor(color) { console.log('traffic-light ', color); } function main() { changeColor('red'); setTimeout(()=>{ changeColor('yellow'); setTimeout(() => { changeColor('green'); setTimeout(main, 2000); }, 1000); }, 2000); } main();
Promise implementation
Use Promise to write the next color change in then, and finally use recursion to complete the loop.
function sleep(duration){ return new Promise(resolve => { setTimeout(resolve, duration); }) } function changeColor(duration,color){ return new Promise(resolve => { console.log('traffic-light ', color); sleep(duration).then(resolve); }) } function main() { return new Promise(resolve => { changeColor(2000, 'red').then(() => { changeColor(1000, 'yellow').then(() => { changeColor(3000, 'green').then(() => { main(); }) }) }) }) }main();
async await implementation
Using async await can avoid a series of .then.then.then in Promise, and there is no need for recursion. You can use while to implement loops .
function sleep(duration) { return new Promise(resolve => { setTimeout(resolve, duration); }) } async function changeColor(color, duration) { console.log('traffic-light ', color); await sleep(duration); } async function main() { while (true) { await changeColor('red', 2000); await changeColor('yellow', 1000); await changeColor('green', 3000); } } main();
Recommended study: "javascript basic tutorial"
The above is the detailed content of How to implement traffic lights in javascript. For more information, please follow other related articles on the PHP Chinese website!