使用setTimeout、Promise、async await 三种方式实现红绿灯代码,红灯2秒,黄灯1秒,绿灯3秒,循环改变颜色。改变颜色的方法,就简单写成打印出颜色。
setTimeout实现
使用setTimeout是最基本的实现方式,代码如下,使用递归来实现循环改变颜色。
function changeColor(color) {
console.log('traffic-light ', color);
}
function main() {
changeColor('red');
setTimeout(()=>{
changeColor('yellow');
setTimeout(() => {
changeColor('green');
setTimeout(main