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 thegetNum
function, causing the stack to exhaust. Replace the function callgetNum()
with the function referencegetNum
:Link to documentation of
setTimeout
.The problem is your call to
setTimeout
is invokinggetNum
instead of scheduling it for execution. This leads to infinite recursion and a stack overflow. Try the following insteadsetTimeOut
should besetTimeout