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) { // 這將定時(shí)器設(shè)置為從5倒數(shù)到0 await new Promise(resolve => setTimeout(resolve, 1000)); if (state.counter) state.gameStartTimer--; // if語句確保在gameStartTimer達(dá)到0時(shí)獲取nowTime if (state.gameStartTimer == 0) { let timeNow = new Date().getTime(); state.nowTime = timeNow; } } state.counter = false; // 我想在這里啟動(dòng)第二個(gè)定時(shí)器,每秒倒計(jì)時(shí)一次,直到randomNumber狀態(tài)達(dá)到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.
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); }