我正在尝试使用Math.random()生成随机数,这些随机数以随机间隔记录/写入 ...
我写了以下内容:
function ranNum () {
setInterval( function () {
var myNum = Math.round(Math.random()*100000);
document.write(myNum+' ');
return myNum;
}, ranNum)
}
ranNum();
但是间隔不是随机的,实际上它们似乎是零或零,因为打印了无穷无尽的数字......我想这是不可能调用一个新的ranNum函数实例所以setInterval的第二个参数是0或总是相同..
我被告知递归将是解决方案,但未能实现它。
答案 0 :(得分:1)
正如monkeyinsight指出的那样,使用setTimeout
:
function ranNum () {
setTimeout( function () {
var myNum = Math.round(Math.random()*100000);
document.write(myNum+' ');
ranNum(); //This makes the function call `recursive` (in a broad sense)
return myNum;
}, Math.round(Math.random()*10000) // The function in the setTimeout will be called in 0-10000ms
);
}
ranNum();
答案 1 :(得分:1)
如果您想要随机间隔,请使用重复的setTimeout
。 setInterval
只是在同一时间间隔内重复。
function ranNum () {
schedule();
function schedule() {
setTimeout(go, Math.random() * 10000);
}
function go() {
var myNum = Math.round(Math.random()*100000);
document.write(myNum+' ');
schedule();
// No return, it doesn't make any sense to return something from a timer function
}
}
旁注:您不希望document.write
这样做。在第一个定时器函数调用后,document.write
将对您的文档进行替换。相反,请使用现代DOM技术,例如appendChild
或insertAdjacentHTML
。
var counter = 20;
function ranNum () {
schedule();
function schedule() {
setTimeout(go, Math.random() * 10000);
}
function go() {
var myNum = Math.round(Math.random()*100000);
display(myNum+' ');
if (--counter > 0) { // For the snippet, stop after 20
schedule();
}
// No return, it doesn't make any sense to return something from a timer function
}
}
function display(msg) {
document.body.insertAdjacentHTML("beforeend", msg);
}
ranNum();