无限循环显示随机数js

时间:2013-12-16 18:26:56

标签: javascript loops random settimeout

我的代码无法正常工作。它必须显示一个随机数,但每隔几毫秒就会更改,但不会停止。

这是DOM:

<p>Random number:</p>
<p id="random_number"></p>

我的剧本:

var random_script = function() {
    while (true) {
        setTimeout(function(){
           var t = Math.round(Math.random() * (100 - 1) + 1);
           document.getElementById("random_number").innerHTML = t;
        }, 1000);
    }
}();

但是Chrome一直在崩溃。有什么帮助吗?

3 个答案:

答案 0 :(得分:2)

    setInterval(function(){
       var t = Math.round(Math.random() * (100 - 1) + 1);
       document.getElementById("random_number").innerHTML = t;
    }, 1000);

答案 1 :(得分:2)

我建议:

(function(el, interval) {
    window.setInterval(function(){
        // you can use the math you were using, but I can't see the necessity
        el.textContent = Math.floor(Math.random() * 100);
    }, interval);
})(document.getElementById('random_number'), 1000);

JS Fiddle demo

此方法是一个立即调用的函数表达式,它将相关参数传递给函数,然后函数设置要在定义的时间间隔执行的函数。这使用window.setInterval以重复的间隔重复/重新调用传递的函数,而不是在间隔之后执行一次(如setTimeout那样)。

参考文献:

答案 2 :(得分:1)

http://jsfiddle.net/5FE8p/会有所帮助。

function myFunc ()
{
    setTimeout(function() {
        var t = Math.round(Math.random() * (100 - 1) + 1);
        console.info(t);
        document.getElementById("random_number").innerHTML = t;
        myFunc();
    }, 1000);
}
myFunc();

你不应该一次多次调用settimeout。它们是异步触发的......