23

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>
ruffin
  • 15,005
  • 8
  • 80
  • 126
Howdy_McGee
  • 10,036
  • 28
  • 103
  • 179

3 Answers3

42

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.

Rob W
  • 328,606
  • 78
  • 779
  • 666
10

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);
JaredPar
  • 703,665
  • 143
  • 1,211
  • 1,438
4

setTimeOut should be setTimeout

Hogan
  • 65,989
  • 10
  • 76
  • 113