我正在尝试编写最终构成简单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);
&#13;
<div id="numbers-display"></div>
&#13;
是否有人能够指出为什么这个功能只显示一个随机数而不是30个随机数?再次感谢您的帮助。
答案 0 :(得分:2)
在每次迭代中尝试await
承诺,否则它们将立即运行(setTimeout
s当前全部在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
循环块不应以分号结尾,也不应用函数声明。