I have a Vue project with the following status in Vuex storage:
state: { gameStartTimer: 5, counter: false, randomNumber: Number, clickAlert: false }
Now, in actions
, I have the following:
actions: { async startCounter({ state }) { state.counter = true; state.clickAlert = false; while (state.gameStartTimer > 0 && state.counter) { // 这将定时器设置为从5倒数到0 await new Promise(resolve => setTimeout(resolve, 1000)); if (state.counter) state.gameStartTimer--; // if语句确保在gameStartTimer达到0时获取nowTime if (state.gameStartTimer == 0) { let timeNow = new Date().getTime(); state.nowTime = timeNow; } } state.counter = false; // 我想在这里启动第二个定时器,每秒倒计时一次,直到randomNumber状态达到0 await new Promise(resolve => setTimeout(resolve, 1000)); if (state.clickAlert) state.randomNumber--; if (state.randomNumber == 0) { state.clickAlert = true; } } }, }
The problem I'm facing is that the first timer is wrapped in a while loop, which is exactly what I want, so that the game starts at 5 and counts down to 0.
Then I want the second timer (using randomNumber as duration) to run in the background and then set the clickAlert state to true.
However, I cannot make the second timer run in the async/await method. I'm not quite sure what the syntax or logic issue is.
Any tips would be greatly appreciated.
P粉3333954962024-03-31 00:17:48
The obvious solution seems to be to put the second timer also in a while
loop.
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 is functionally equivalent to the following code:
while (state.randomNumber > 0) { setTimeout(() => { state.randomNumber--; }, 1000); }