Thursday, August 18, 2022

[FIXED] how to slow down the output of a list using setTimeout inside of JS function

Issue

This program will output the combinations of 4 elements of the 5 elements contained inside of the array. But it does that instantly and i want it to do that slower , waiting 1 second after each row. I have already tried in many ways to add setTimeout(function()content,1000*i) it just doesn't work for me and related question couldn't help with that. Can anyone help with a solution?

const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const three = [];
three.length = 4;

function combine(a, b, c) {
  if (b === 0) {
    console.log(`${three.join(" ")}`);
    return;
  }
  for (let i = c; i <= a.length - b; i++) {
    three[three.length - b] = a[i];
    combine(a, b - 1, i + 1);
  }
}

combine(vegetables, three.length, 0);


Solution

You can try something like this:

const vegetables = ["carrot", "tomatoes", "potatoes", "celery", "pepper"];
const three = [];
const combined = [];
three.length = 4;

function sleep(ms) {
  return new Promise(function (resolve) {
    setTimeout(resolve, ms);
  });
}

function combine(a, b, c) {
  if (b === 0) {
    combined.push(`${three.join(" ")}`);
    return;
  }

  for (let i = c; i <= a.length - b; i++) {
    three[three.length - b] = a[i];
    combine(a, b - 1, i + 1);
  }
}

(async function main() {
  console.log('started');
  combine(vegetables, three.length, 0);

  for (const entry of combined) {
    console.log(entry);
    await sleep(1000);
  }
})();



Answered By - Mehmet Baker
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.