【面试题】循环打印红绿灯

循环打印红绿灯

点击打开视频讲解更加详细

红灯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>

效果:
在这里插入图片描述
点击打开视频讲解更加详细

posted @ 2022-08-21 08:41  程序猿咬棒棒糖拽天下  阅读(149)  评论(0编辑  收藏  举报