PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, August 18, 2022

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

 August 18, 2022     arrays, delay, function, javascript, output     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing