【问题标题】:How to start a second timer after the first timer expires in Vuex?如何在Vuex中的第一个计时器到期后启动第二个计时器?
【发布时间】:2021-09-23 03:56:30
【问题描述】:

我有一个 Vue 项目,在 Vuex 商店中我有这些状态:

state: {
  gameStartTimer: 5,
  counter: false,
  randomNumber: Number,
  clickAlert: false
}

现在,在actions 中,我有以下内容:

actions: {
    async startCounter({ state }) {
      state.counter = true;
      state.clickAlert = false;
      while (state.gameStartTimer > 0 && state.counter) {

        // this sets the timer to count down from 5 to 0
        await new Promise(resolve => setTimeout(resolve, 1000));
        if (state.counter)
          state.gameStartTimer--;

        // the if-statement ensures nowTime is acquired upon gameStartTimer reaches 0
        if (state.gameStartTimer == 0) {
          let timeNow = new Date().getTime();
          state.nowTime = timeNow;
        }
      }
      state.counter = false;

      // I want to start a second timer here which counts down every second 
      // until the randomNumber state reaches 0
        await new Promise(resolve => setTimeout(resolve, 1000));
        if (state.clickAlert)
          state.randomNumber--;

        if (state.randomNumber == 0) {
          state.clickAlert = true;
        }
      }

    },
}

我面临的问题是第一个计时器被包裹在一个while循环中,这是我想要的,所以游戏开始从5倒计时到0。

然后,我想要第二个计时器(randomNumber 用于持续时间)在后台运行,然后将 clickAlert 状态设置为 true。

但是,我根本无法在 async/await 方法中运行第二个计时器。我不太确定语法或逻辑问题是什么。

感谢任何提示。

【问题讨论】:

    标签: javascript vue.js async-await promise vuex


    【解决方案1】:

    显而易见的解决方案似乎是将第二个计时器也包含在 while 循环中。

    while (state.randomNumber > 0) {
        await new Promise(resolve => setTimeout(resolve, 1000));
        state.randomNumber--;
    
        if (state.randomNumber === 0) {
            state.clickAlert = true;
        }
    }
    

    async/await 只是一种避免回调函数的方法。它在功能上等同于:

    while (state.randomNumber > 0) {
        setTimeout(() => {
            state.randomNumber--;
        }, 1000);
    }
    

    【讨论】:

    • 谢谢,我之前测试过它并没有用(顺便说一下,它实际上是有效的,只是它有一个错误并且这个问题是我刚刚发现的另一个问题的次要问题)。真正的问题是倒计时是以毫秒而不是秒为单位倒计时,这就是为什么 clickAlert 从未改变(或者更确切地说它会改变但我必须等待 1,000 秒)。看起来像一个简单的问题要解决 - 主要问题是我直到现在才发现这个问题。感谢您确认语法/逻辑!它有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-08
    相关资源
    最近更新 更多