skip to Main Content

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


  1. You can use SetInterval function for that, e.g:

    setInterval(async () => {
      await checkWinner();
    }, 1000)
    

    This code will run the checkWinner() function every second.

    Login or Signup to reply.
  2. 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 the players 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.

    Login or Signup to reply.
  3. setInterval(async () => {
      await myAsyncFunction();
    }, 1000); // Runs myAsyncFunction() every second
    

    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

    Login or Signup to reply.
  4. The way you run code repeatedly in JavaScript is by using a setInterval() timer.

    setInterval(() => {
      // Your recurring code
    }, 3000);
    

    Note that this will run until you reload the page or stop the interval:

    const myInterval = setInterval(() => {
      // Your recurring code
    }, 3000);
    
    clearInterval(myInterval); // this line will stop the interval when you call it.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search