我正在尝试创建一些代码,这些代码将一个接一个地显示随机数,并且数字更改之间的差距为1.5秒。在这一点上,我已经尝试了大约一百万种不同的方法而且都没有用。我很沮丧,因为我已经学习了几个月的代码,并且认为我已经掌握了这样简单的东西。无论如何,这是代码:
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 runOnInterval(content) {
setInterval(content, 1500);
};
runOnInterval(runRandomNumbers(numbers));
有人能告诉我这有什么问题吗?非常感谢!
答案 0 :(得分:4)
您需要将函数runRandomNumbers
传递给runOnInterval()
,而不是其返回值runRandomNumbers(numbers)
。请参阅以下代码:
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 runOnInterval(fn, numbers) {
setInterval(function() { fn(numbers) }, 1500);
};
runOnInterval(runRandomNumbers, numbers);
<div id="numbers-display"></div>
此外,我更改了runOnInterval
,以便它接受函数和数字数组作为参数。
答案 1 :(得分:2)
.setInterval() 需要将函数 引用 传递给它,而不是语句。
当JavaScript编译器首先读入代码时,语句runRandomNumbers(numbers)
立即执行(因此您生成一个随机数并打印到屏幕上),然后返回它的值(即{{ 1}})实际上被传递并存储为定时器的回调。当计时器达到其间隔时,没有任何东西(undefined
)可以调用,所以该函数运行一次,你看到一个数字,但那就是它。
解决方案是在函数中定期包装您想要执行的代码,以便将该函数引用传递给undefined
。
此外,如果要显示生成的数字列表,如果要保留旧值并且只是连接到它,则需要使用.setInterval()
设置元素的内容。
注意:
+=
包含HTML,因为它强制浏览器解析字符串
当没有任何HTML时,HTML会浪费资源。
相反,请使用.innerHTML
来获取/设置不要使用的字符串
包括任何HTML。
.textContent
&#13;
var element = document.getElementById("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 runRandomNumbers (array) {
element.textContent += array[Math.floor(Math.random()*10)];
}
// A function is expected as the argument here. That function
// will be stored as the callback for the timer.
function runOnInterval(callbackFunction) {
setInterval(callbackFunction, 1500);
}
// We'll pass a function as the datat for the argument
runOnInterval(function(){ runRandomNumbers(numbers) });
&#13;
答案 2 :(得分:1)
setInterval
期望它应该调用一个(callback-)函数。因此函数名称或匿名函数。
无论
function doEverySecondAndHalf() {
runRandomNumbers(numbers);
}
runOnInterval(doEverySecondAndHalf); // Note the missing () after doEverySecondAndHalf
或者
runOnInterval(function() {
runRandomNumbers(numbers);
});