尝试使用 javascript 循环显示随机数,无法理解为什么只显示一个数字



我正在尝试编写代码,最终将形成一个简单的n-back游戏的基础。现在我只是想让 30 个随机数在短暂的延迟后一个接一个地显示(您可能已经看过我之前与这个小项目相关的问题 - 如果是这样,谢谢大家的输入,因为它非常有帮助(。我能够使用 setInterval 方法完全按照我想要的方式循环显示,但这并不好,因为出于某种原因,它不接受回调函数来跟踪间隔数,然后调用 clearInterval 方法。换句话说,数字继续无限期显示,这不是我想要的。我正在尝试使用使用 for 循环的函数来实现同样的事情,但这也不起作用,因为由于某种原因该函数无法正常工作并且只显示一个随机数然后停止。请参阅下面的代码:

var javascriptElement = "numbers-display";
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
//This function takes a single argument and displays it in the browser.
function displayContent (content) {
document.getElementById(javascriptElement).innerHTML = content;
};
function runRandomNumbers (array) {
displayContent(array[Math.floor(Math.random()*10)]);
};
function runOnTimeOut(fn, arg) {
setTimeout(function() {
fn(arg);
}, 2000);
};
//this is the function that isn't doing what I want it to do.
function runOnLoop(fn, arg1, arg2) {
for (i = 0; i < 30; i++) {
fn(arg1, arg2);
};
}
runOnLoop(runOnTimeOut, runRandomNumbers, numbers);
<div id="numbers-display"></div>

有谁能指出为什么这个函数只会显示一个随机数而不是 30 个随机数?再次感谢您的帮助。

尝试在每次迭代中awaiting promise,否则它们将同时运行(setTimeout目前在 2000 毫秒后一起触发(:

var javascriptElement = "numbers-display";
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
//This function takes a single argument and displays it in the browser.
function displayContent (content) {
document.getElementById(javascriptElement).innerHTML = content;
}
function runRandomNumbers (array) {
displayContent(array[Math.floor(Math.random()*10)]);
}
function runOnTimeOut(fn, arg) {
return new Promise(resolve => 
setTimeout(() => {
fn(arg);
resolve();
}, 500)
);
}
//this is the function that isn't doing what I want it to do.
async function runOnLoop(fn, arg1, arg2) {
for (let i = 0; i < 30; i++) {
await fn(arg1, arg2);
}
}
runOnLoop(runOnTimeOut, runRandomNumbers, numbers);
<div id="numbers-display"></div>

另请注意,循环块不应for分号结尾,函数声明也不应以分号结尾

最新更新