Maximum Call Stack Size Exceeded During a setTimeout Call

71,839

Solution 1

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.

Solution 2

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);

Solution 3

setTimeOut should be setTimeout

Share:
71,839

Related videos on Youtube

Howdy_McGee
Author by

Howdy_McGee

I'm a Web Developer who is constantly learning the trade. I've built and manage 100+ WordPress websites with the help of the talented Web Designers around me. I'm currently looking for ways I can help the WordPress community grow and maintain its awesomeness! ~ Alex

Updated on May 11, 2020

Comments

  • Howdy_McGee
    Howdy_McGee about 4 years

    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>
    
    • maple_shaft
      maple_shaft over 12 years
      You realize that your function getNum() will get stuck in an endless recursive loop right?
  • Howdy_McGee
    Howdy_McGee over 12 years
    Ha! yeah that got rid of the error but that didn't make it start incrementing. Ima keep at it thanks!
  • Rob W
    Rob W over 12 years
    Now it increases. You have to assign the num variable.
  • parsecer
    parsecer about 6 years
    What if a getNum function takes arguments?
  • ss1
    ss1 almost 5 years
    @parsecer You can add them like this: setTimeout(getNum, 4000, arg1, arg2, arg3, etc)