红绿灯 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();

 

posted on 2019-07-03 08:51  含蓄的龅牙妹  阅读(144)  评论(0编辑  收藏  举报

导航