下面这是一个用promise写的小案例 红绿灯 当成功时调用resolve(); 使用promise的then方法 接收结果
function redFunc(){
$("#redLight").style.background=“orangered”;
let count=6;
$("#redLight").innerHTML=count;
return new Promise(function(resolve, reject){
let myTimer=setInterval(()=>{
count–;
$("#redLight").innerHTML=count;
if(count<=0){
count=0;
clearInterval(myTimer);
$("#redLight").innerHTML=" “;
$(”#redLight").style.background=“white”;
resolve();
}
},1000);
})
}
function greenFunc(){
$("#greenLight").style.background=“lightgreen”;
let count=4;
$("#greenLight").innerHTML=count;
return new Promise(function(resolve, reject){
let myTimer=setInterval(()=>{
count--;
$("#greenLight").innerHTML=count;
if(count<=0){
count=0;
clearInterval(myTimer);
$("#greenLight").innerHMTL=" ";
$("#greenLight").style.background="white";
resolve();
}
},1000);
})
}
function yellowFunc(){
$("#yellowLight").style.background=“yellow”;
let count=2;
$("#yellowLight").innerHTML=count;
return new Promise(function(resolve, reject){
let myTimer=setInterval(()=>{
count--;
if(count<=0){
count=0;
clearInterval(myTimer);
$("#yellowLight").innerHTML=" ";
$("#yellowLight").style.background="white";
resolve();
}
$("#yellowLight").innerHTML=count;
},1000);
})
}
function shine(){
redFunc().then(greenFunc).then(yellowFunc).then(shine);
}
window.οnlοad=function(){
shine();
}
function $(str){
if(str.charAt(0)=="#"){
return document.getElementById(str.substring(1));
}else if(str.charAt(0)=="."){
return document.getElementsByClassName(str.substring(1));
}else{
return document.getElementsByTagName(str);
}
}