本文介绍了setTimeout呼叫期间超出最大呼叫堆栈大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  

里面 getNum ,你直接调用 getNum 函数,导致堆栈耗尽。将函数调用 getNum()替换为函数引用 getNum :

  function getNum()//获取由页面加载触发,因此innerHTML工作
{
num + = 7; //增加并分配变量
document.getElementById('counter')。innerHTML = num;
setTimeout(getNum,4000); //< - 正确的方式
}

链接到。


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:

<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>
解决方案

Inside getNum, you're directly invoking the getNum function, causing the stack to exhaust. Replace the function call getNum() with the function reference 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呼叫期间超出最大呼叫堆栈大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 02:57