I would like this function below to be running throughout the game, so when a player has no people left it will declare the winner. Is there a way to do this?
async function checkWinner() {
if (document.getElementById('player1').innerText === '0') {
message.innerHTML = `<p>${players[1]} you have won the game</p>`;
await sleep(3000);
window.location.reload();
}
if (document.getElementById('player2').innerText === '0') {
message.innerHTML = `<p>${players[0]} you have won the game</p>`;
await sleep(3000);
window.location.reload();
}
}
4
Answers
You can use SetInterval function for that, e.g:
This code will run the
checkWinner()
function every second.Can you explain a bit more about the game and maybe share more code that would explain the usage of
checkWinner()
.From your tags it seems like you’re creating a game without the use of any frameworks, am I right? If so, you somehow need to add
checkWinner()
to the function that manipulates theplayers
variable.Using an interval for this would either be too slow for the game to function correctly or it would be a terrible waste of resources.
In this example, we pass an anonymous async function to setInterval(). Inside the function, we call myAsyncFunction() using the await keyword to wait for it to complete before moving on to the next interval.
Keep in mind that if myAsyncFunction() takes longer than the interval you specified, multiple invocations of the function may run concurrently, which could lead to unexpected behavior. To prevent this, you can use a locking mechanism such as a mutex to ensure that only one invocation of the function is running at a time.
Also note that using setInterval() with an asynchronous function may not be the most efficient way to accomplish your task, especially if the function takes a long time to complete or if you need to handle errors. In such cases, you may want to consider using a more robust scheduling library such as node-cron or agenda
The way you run code repeatedly in JavaScript is by using a
setInterval()
timer.Note that this will run until you reload the page or stop the interval: