Uncaught RangeError: Maximum call stack size exceeded on javascript

- 1 answer

Ad

Well, I'm trying make a countdown to Christmas and I'm getting this error I'm new in this, please help

<script>
function Falta() {
var d = new Date();
var di = 25 - d.getDate();
var ho = 23 - d.getHours();
var mi = 59 - d.getMinutes();
var se = 59 - d.getSeconds();
var di = checkTime(di);
var ho = checkTime(ho);
var mi = checkTime(mi);
var se = checkTime(se);
var t = setTimeout(Falta(), 500)
document.getElementById("demo").innerHTML = di + ":" + ho + ":" + mi + ":" + se;
}
function checkTime(i) {
    if (i < 10) {i = "0" + i};
    return i;
}
</script>
<div id="demo" onclick="Falta()">Click!</div>
Ad

Answer

Ad

There are a few mistakes with your code.

  • Missing semicolons.
  • Inline event handlers (while it works, it's not recommended).
  • Excecuting the Falta() function instead of just passing it by reference.
  • Reuse of the var keyword once the variable has been set.

I've set up a JSFiddle with a working demo of your idea.

HTML

<div id="demo">
  Click!
</div>

Simple and clean, no inline event handling, this allows to separate your HTML from your JavaScript.

JavaScript

demoDiv = document.getElementById("demo"); //added a reference for the div
demoDiv.addEventListener("click",Falta); //added the onclick event

function Falta() {
  var d = new Date();
  var di = 25 - d.getDate();
  var ho = 23 - d.getHours();
  var mi = 59 - d.getMinutes();
  var se = 59 - d.getSeconds();
  di = checkTime(di); //removed var keywords
  ho = checkTime(ho);
  mi = checkTime(mi);
  se = checkTime(se);
  setTimeout(Falta, 500); //added semicolon, removed parenthesis
  demoDiv.innerHTML = di + ":" + ho + ":" + mi + ":" + se;
}

function checkTime(i) {
  if (i < 10) {
    i = "0" + i
  };
  return i;
}

So, first of all I've set up a reference for the <div> element since we'll be calling it a few times.

After that I've set the click event via the addEventListener() function, and passed the Falta() function as a reference (that would be without the parenthesis).

I've also removed the second var keywords you used while updating your variable names, it should only be use to declare a variable, not every time you change it's value.

Finally I passed the Falta() function to the setTimeout() as a reference, instead of executing it.

Hope this helps!

Note: it is worth noting that JSFiddle automatically wraps your code inside the window.onload event, and thus transferring your code to another enviroment may not work as it's not waiting for the DOM to load before searching for the <div> element.

Ad
source: stackoverflow.com
Ad