0

I have a javascript function that keeps calling itself after a timeout. (I'm not using setInterval, as the execution of the function can take a while and it must be ensured that after ending executing the timeout starts.)

I noticed that when I do s.th. like this (below), the JS call stack keeps increasing forever and I fear this might run into out of memory or call stack exceed or whatever JS might do in such a case.

function doSomething() {
  var newdiv = document.createElement("DIV");
  newdiv.appendChild(document.createTextNode("some text"));
  document.body.appendChild(newdiv);
  setTimeout(doSomething, 1000);
}

Actually I thought that setTimeout calls the function independently from the current function context.

How can I avoid the call stack from increasing infinitely?

Using doSomthing.bind(null) as suggested here in does not help, the call stack also inceases:

function doSomething() {
  var newdiv = document.createElement("DIV");
  newdiv.appendChild(document.createTextNode("some text"));
  document.body.appendChild(newdiv);
  setTimeout(doSomething.bind(null), 1000);
}

How can I avoid the call stack from increasing infinitely? Thanks!

Peter T.
  • 2,927
  • 5
  • 33
  • 40
  • 1
    That won't do what you're afraid it might do. Those calls are not really recursive. Only one will be active at any given time. If something is making you think the stack is filling up, it's not this code doing it. – Pointy Mar 01 '18 at 15:22
  • 1
    Those entries you're seeing in the devtools stack aren't really stack entries, and you're not the first to be confused by them; see my answer on the [linked question](https://stackoverflow.com/questions/48736331/by-using-javascript-recursive-settimeout-function-is-it-risky-to-get-the-stacko) for more. – T.J. Crowder Mar 01 '18 at 15:28
  • Thank you, I hoped it would be this way. :-) – Peter T. Mar 01 '18 at 15:37

0 Answers0