Search code examples
javascriptfunctionloopsparadigms

Leaving recursive functions running forever?


I came across a function where it had a setTimeout inside with a timeout growing exponentially (timeout *= 2).

let timeout = 10000
function foo() {
    // doSomething without breaking, returning
    setTimeout(foo, timeout)
    timeout *= 2;
}
foo()

It seems that this should not be a problem and intuitively feels like setInterval is kinda doing the same already (having an infinite loop until it's cancelled if ever), however, my question is in the approach itself.

  • Is this something that could lead to memory leaks?
  • Is it better/clearer to still limit the number of calls to the function?
  • Would other languages use such approach or are there different mindsets outside of JS world?

Solution

  • This is not a recursive function call. The call to setTimeout will cause foo to be called by the JavaScript event loop at a later time.

    This code will not cause a stack overflow or any such problems. It should be completely safe.

    To understand how this works in-depth, I suggest reading up on the JS event loop and microtasks.