如何在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);
}
})();
相关文章