需求:做一个红绿灯组件,绿灯亮10秒,黄灯亮5秒,红灯亮2秒,循环往复
//先写一个高亮工具函数
function lightenTool(lightType){
const lightDomArr= [...document.getElementsByClass('lights')],
currentLight = document.getElementsByClass(lightType)[0];
//先清除所有元素高亮类名
lightDomArr.forEach((elem)=>{
elem.classList.remove('lighten')
})
//给当前颜色信号灯添加高亮类名
currentLight.classList.add('lighten')
cosnole.log(lightType)
}
// 1、传统递归不嵌套方法
funcion lightsGo(){
lightenTool('green')
setTimeout(function(){
lightenTool('yellow')
},10000)
setTimeout(function(){
lightenTool('red')
lightsGo()
},15000)
setTimeout(function(){
lightsGo()
},17000)
}
//2、传统回调嵌套方法,复杂、难维护
function lightsGo(){
lightenTool('green')
setTimeout(function(){
lightenTool('yellow')
setTimeout(function(){
lightenTool('red')
setTimeout(function(){
lightsGo()
},2000)
},5000)
},10000)
}
//3、promise链式调用
function lightenTool(type){
console.log(type)
}
function sleep(time){
return new Promise((resolve)=>{
setTimeout(()=>{
resolve()
},time)
})
}
//function promiseResolve(callback,time){
// return new Promise((resolve)=>{
// setTimeout(()=>{
// console.log(callback)
// resolve()
// },time)
// })
//}
// 这个函数没有遵循单一功能原则,把回调函数和异步等待功能耦合在一起,对后续使用造成了困难
function lightsGo(){
lightenTool('green');
sleep(10000)
.then(()=>{
lightenTool('yellow');
return sleep(5000)
})
.then(()=>{
lightenTool('red');
return sleep(2000)
})
.then(()=>{
lightsGo()
})
}
lightsGo()
//3.async和await同步写法
function lightenTool(type){
console.log(type)
}
function sleep(time){
return new Promise((resolve)=>{
setTimeout(()=>{resolve()},time)
})
}
async function lightsGo(){
lightenTool('green')
await sleep(10000);
lightenTool('yellow')
await sleep(5000);
lightenTool('red')
await sleep(2000);
lightsGo()
}
//还可以改进用while do来写,不用递归
async function lightsGo(){
while(true){
lightenTool('green')
await sleep(10000);
lightenTool('yellow')
await sleep(5000);
lightenTool('red')
await sleep(2000);
}
}