Home > Back-end >  Loop function ith timer before if statement
Loop function ith timer before if statement

Time:07-05

btnRoll.addEventListener ('click', function() {
if (isPlaying) {
  diceElement.classList.remove ('hidden');
  function changeDiceImage () {
    // Display number on the dice
    const diceNumber = Math.trunc (Math.random () * 6)   1;
    diceElement.src = `dice${diceNumber}.png`;
    i  ;
    let timer = setTimeout (changeDiceImage, 200);
    if (i === 5) {
      clearTimeout (timer);
      number = diceNumber;
    }
    timer;
  }
  let i = 0;
  let number = 0;
  changeDiceImage ();
  if (number !== 1) {
    currentScore  = number;
    document.getElementById (`current--${activePlayer}`).textContent = currentScore;
  } else {
    switchActivePlayer ();
  }
}
})

I try to loop function (that randomly change images with dice) and also last dice number go to number then to score. In result i receive NaN value instead of number. How to fix the problem?

CodePudding user response:

First, a couple tools...

A function that returns a promise which resolves after ms...

async function after(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

A function that returns a randomly shuffled array of [1..6], due to Mike Bostock...

function shuffleDie() {
  let array = [1,2,3,4,5,6]
  let m = 6, t, i;

  while (m) {
    i = Math.floor(Math.random() * m--);
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }
  return array;
}

The OP's aim: present a random sequence of die images and return (a promise that resolves to) the last number in the random sequence...

async function changeDiceImage(diceElement) {
  const numbers = shuffleDie();
  for (let number of numbers) {
    diceElement.src = `dice${number}.png`;
    await after(ms);
  }
  return numbers[5];  // resolve to the last number
}

Use these to clean up the eventListener significantly...

btnRoll.addEventListener ('click', async () => {
  if (isPlaying) {
    diceElement.classList.remove ('hidden');
    let number = await changeDiceImage(diceElement);

    if (number !== 1) {
      currentScore  = number;
      document.getElementById (`current--${activePlayer}`).textContent = currentScore;
    } else {
      switchActivePlayer ();
    }
  }
})
  • Related