Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximum Call Stack Size Exceeded During a setTimeout Call

Tags:

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>
like image 825
Howdy_McGee Avatar asked Jan 04 '12 18:01

Howdy_McGee


People also ask

How do I fix error in maximum call stack size exceeded?

The call stack is limited in size, and when it's exceeded, the RangeError is thrown. This can happen when a deeply nested function is called, or when a lot of new variables are created. The most common way to fix this error is to reduce the number of function calls, or to limit the number of variables that are created.

What causes maximum call stack size exceeded?

The JavaScript RangeError: Maximum call stack size exceeded is an error that occurs when there are too many function calls, or if a function is missing a base case.

What is maximum call stack?

It means that somewhere in your code, you are calling a function which in turn calls another function and so forth, until you hit the call stack limit. This is almost always because of a recursive function with a base case that isn't being met.

How do I fix uncaught RangeError max call stack size exceeded see JavaScript console for details?

The "RangeError: Maximum call stack size exceeded" error occurs when a function is called so many times that the invocations exceed the call stack limit. To solve the error, specify a base case that has to be met to exit the recursion.


3 Answers

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.

like image 70
Rob W Avatar answered Oct 29 '22 13:10

Rob W


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

setTimeout(getNum, 4000);
like image 43
JaredPar Avatar answered Oct 29 '22 14:10

JaredPar


setTimeOut should be setTimeout

like image 43
Hogan Avatar answered Oct 29 '22 13:10

Hogan