红绿灯 promise和原始方式实现

Promise 方式 async+await

function sleep(duration){
    return new Promise(function(resolve){
        setTimeout(resolve, duration);
    })
}
async function changeColor(duration,color){
    document.getElementById("traffic-light").style.background = color;
    await sleep(duration);

}
async function main(){
    while(true){
        await changeColor(3000,"green");
        await changeColor(1000, "yellow");
        await changeColor(2000, "red");
    }
}
main()

原始方式

function color () { 
   console.log('green');

   setTimeout(() => {
      console.log('yellow');

      setTimeout(() => {
         console.log('red');

         setTimeout(color, 2000);
      }, 1000)
   }, 3000);
}
color();

转载于:https://www.cnblogs.com/moli-/p/11124298.html

猜你喜欢

转载自blog.csdn.net/weixin_33924312/article/details/94545830