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!

3
  • 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. Commented Mar 1, 2018 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 for more. Commented Mar 1, 2018 at 15:28
  • Thank you, I hoped it would be this way. :-) Commented Mar 1, 2018 at 15:37

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.