【面试题】循环打印红绿灯
循环打印红绿灯
红灯3秒后变成绿灯
绿灯5秒后变成黄灯
黄灯2秒后变成红灯
案例:
<template>
<div id="app">
<div>循环打印红绿灯</div>
<div>红灯3秒后变成绿灯</div>
<div>绿灯5秒后变成黄灯</div>
<div>黄灯2秒后变成红灯</div>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
}
},
mounted() {
// this.red()
this.light()
},
methods:{
//红灯
red(){
return new Promise((resolve) => {
console.log('当前是红灯,3秒后变成绿灯')
setTimeout(() => {
const geeenPromise = this.geeen()
resolve(geeenPromise)
},3000)
})
},
//绿灯
geeen(){
return new Promise((resolve) => {
console.log('当前是绿灯,5秒后变成黄灯')
setTimeout(() => {
const yellowPromise = this.yellow()
resolve(yellowPromise)
},3000)
})
},
//黄灯
yellow(){
return new Promise((resolve) => {
console.log('当前是黄灯,2秒后变成红灯')
setTimeout(() => {
const redPromise = this.red()
resolve(redPromise)
},3000)
})
},
//封装公共方法
timer(color,delay,next){
return new Promise((resolve) => {
console.log(`当前是${color}灯,${delay}秒后变成${next}灯`)
setTimeout(() => {
resolve()
},delay * 1000)
})
},
async light(){
await this.timer('红',3,'绿')
await this.timer('绿',5,'黄')
await this.timer('黄',2,'红')
await this.light()
},
}
}
</script>
<style scoped>
</style>
效果:
点击打开视频讲解更加详细