Maximum Call Stack Size Exceeded During a setTimeout Call

后端 未结 3 706
情书的邮戳
情书的邮戳 2020-12-01 14:32

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:


<         


        
相关标签:
3条回答
  • 2020-12-01 14:41

    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.

    0 讨论(0)
  • 2020-12-01 14:46

    setTimeOut should be setTimeout

    0 讨论(0)
  • 2020-12-01 14:47

    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);
    
    0 讨论(0)
提交回复
热议问题