Search code examples
javascriptvue.jsasync-awaitpromisevuex

How to start a second timer after the first timer expires in Vuex?


I have a Vue project, and in the Vuex store I have these states:

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

Now, in the actions, I have the following:

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;
        }
      }

    },
}

The problem I am facing is that the first timer is enveloped in a while-loop, which is what I want, so that the game starts counting down from 5 to 0.

Then, I want a second timer (randomNumber is used for the duration) to run in the background, then turn the clickAlert state to true.

However, I could not get the second timer to run at all inside an async/await method. I am not quite sure what the syntax or logic problem is.

Any tip is appreciated.


Solution

  • The obvious solution seems to be to just wrap the second timer in a while loop too.

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

    async/await is just a way to avoid callback functions. It's functionally equivalent to this:

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