как замедлить вывод списка с помощью setTimeout внутри функции JS - PullRequest
0 голосов
/ 29 февраля 2020

Эта программа выведет комбинации из 4 элементов из 5 элементов, содержащихся внутри массива. Но он делает это мгновенно, и я хочу, чтобы он делал это медленнее, ожидая 1 секунду после каждой строки. Я уже пытался разными способами добавить setTimeout (function () content , 1000 * i), он просто не работает для меня, и связанный с этим вопрос не может помочь с этим. Может кто-нибудь помочь с решением?

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);

Ответы [ 3 ]

1 голос
/ 01 марта 2020

Вы можете попробовать что-то вроде этого:

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);
  }
})();
0 голосов
/ 01 марта 2020

Вы можете использовать для ожидания ...

const veg = ["carrot", "tomatoes", "potatos", "celery", "pepper"];
const combo = [false, true, true, true, true]; // 4 out of 5

const t0 = performance.now();
function display(){
  const t1 = performance.now();
  console.log(filter(veg, combo), ` time = ${t1-t0}`);
}

async function* nextPerm(a){
  do {
    await new Promise(res => setTimeout(res, 1000));
    yield a;
  } while(nextPermutation(a));
}

let g = nextPerm(combo);
(async function() {
  for await (let next_combo of g) {
    display();
  }
})();

function filter(a, select) {
  return a.filter((_e,i) => select[i]);
}

function nextPermutation(array, first = 0, last = array.length-1) {
  if(first>=last){
    return false;
  }
  let i = last;
  for(;;){
    const i1 = i;
    if(array[--i]<array[i1]){
      let i2 = last+1;
      while(array[i]>=array[--i2]);
      [array[i], array[i2]] = [array[i2], array[i]];
      reverse(array, i1, last);
      return true;
    }
    if(i===first){
      reverse(array, first, last);
      return false;
    }
  }
}

function reverse(array, i=0, j=array.length-1) {
  while (i < j)
    [array[i++], array[j--]] = [array[j], array[i]];
}
0 голосов
/ 01 марта 2020

Я считаю, что вы ищете эффект задержки при отображении списка массивов. Все, что вам нужно сделать, это поместить setTimeOut внутрь l oop, и он отлично работает.

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++) {

    setTimeout(()=>{  //------------------------> Place settimeout here
    three[three.length - b] = a[i];
    combine(a, b - 1, i + 1);
    },1000*i)

  }
}

combine(vegetables, three.length, 0);
...