Javascript 在 setTimeout 调用期间超出最大调用堆栈大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8731840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:14:31  来源:igfitidea点击:

Maximum Call Stack Size Exceeded During a setTimeout Call

javascripthtmltime

提问by Howdy_McGee

I'm trying to call my function every 4 seconds so it will increment a number live. For some reason I keep getting errors. Here's my code:

我试图每 4 秒调用一次我的函数,这样它就会实时增加一个数字。出于某种原因,我不断收到错误消息。这是我的代码:

<html>
<head>
<title>Recycle Counter</title>
<script type="text/javascript">
    function rand(from, to)
    {
       return Math.floor(Math.random() * (to - from + 1) + from); // Generates random number
    }   

    var num = rand(10000, 100000);

    function getNum() // Gets triggered by page load so innerHTML works
    {
        document.getElementById('counter').innerHTML = num + 7;
        setTimeOut(getNum(), 4000);
    }   
</script>
</head>
<body onload="getNum()">
    <div id="counter">

    </div>
</body>
</html>

回答by Rob W

Inside getNum, you're directly invoking the getNumfunction, causing the stack to exhaust. Replace the function call getNum()with the function reference getNum:

在内部getNum,您直接调用该getNum函数,导致堆栈耗尽。用getNum()函数引用替换函数调用getNum

function getNum() // Gets triggered by page load so innerHTML works
{
    num += 7;     // Increase and assign variable
    document.getElementById('counter').innerHTML = num;
    setTimeout(getNum, 4000);   // <-- The correct way
}

Link to documentation of setTimeout.

链接到setTimeout.

回答by JaredPar

The problem is your call to setTimeoutis invoking getNuminstead of scheduling it for execution. This leads to infinite recursion and a stack overflow. Try the following instead

问题是您调用的setTimeout是调用getNum而不是安排它执行。这会导致无限递归和堆栈溢出。请尝试以下操作

setTimeout(getNum, 4000);

回答by Hogan

setTimeOutshould be setTimeout

setTimeOut应该 setTimeout