How to use the setInterval function to display a factorial calculation with a 500ms interval in between each value appearing on screen?

SeventhWarhawk :

I need to implement the setInterval function within my program in order to create an interval of 500ms between each value appearing on screen. The program code i am currently using takes an input value from the user and writes out, as well as calculates the factorized answer.

function factorizeFunction(number, numberArray = []) { //this is the function that does the factorization calculations
  if (number == 0 || number == 1) numberArray.push(number);
  else {
    numberArray.push(number);
    factorizeFunction(number - 1, numberArray);
  }
  return numberArray.join(' * ') + ' = ' + numberArray.reduce((a, b) => a * b, 1);
}
document.getElementById("factorialTest").innerHTML = factorizeFunction(number);

I need to have the answer, for Eg: 6 * 5 * 4 * 3 * 2 * 1 = 720 display on my webpage, each value at a time, with a 500ms delay in between displays. So, 6 (500ms delay) * (500ms delay) 5 (500ms delay)... and so forth. I am unsure on how i would go about doing this?

PierreDuc :

Basically, everything you want printed on your screen, the operators and numbers, need to appear in a 500ms delay. Which means it's best to first obtain an array of these elements:

function getFactorElements(factor) {
  // get array like [1, 2, 3, 4]
  const factorArray = Array.from({ length: factor }, (_, i) => i + 1);

  // calculate result
  const result = factorArray.reduce((a, b) => a * b, 1);

  // insert math operators
  const parts = factorArray
    .reverse()
    .map((part) => [ part, part > 1 ? '*' : '=' ])
    .reduce((a, b) => a.concat(b));

  parts.push(result);

  return parts;
}

With this being your HTML

<div id="factorialTest"></div>

You can create another function which accepts an element and the factor:

async function showFactorCalculation(element, factor) {
  element.innerHTML = '';

  for (const part of getFactorElements(factor)) {
    element.innerHTML += ' ' + part;
    await new Promise((resolve) => setTimeout(resolve, 500));
  }
}

Which you should call like this:

showFactorCalculation(document.getElementById('factorialTest'), 9);

And I've got a working stack for you here ;):

stack

I'm using setTimeout because using setInterval is mainly discouraged

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12397&siteId=1