如何在JS函数中使用setTimeout降低列表的输出速度 [英] how to slow down the output of a list using setTimeout inside of JS function

查看:0
本文介绍了如何在JS函数中使用setTimeout降低列表的输出速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该程序将输出数组中包含的5个元素的4个元素的组合。但它会立即这样做,我希望它能更慢地这样做,每行后等待1秒。 我已经尝试了很多方法来添加setTimeout(Function()Content,1000*i)它对我不起作用,相关问题也无法解决。有谁可以帮助解决方案吗?

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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);

推荐答案

您可以尝试这样的操作:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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);
  }
})();

这篇关于如何在JS函数中使用setTimeout降低列表的输出速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆