1

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?
Roland Jegorov
  • 789
  • 1
  • 11
  • 27
  • @RobIII Thanks for the comment. No, it doesn't break there. – Roland Jegorov Jun 04 '18 at 08:50
  • As others pointed out, I was wrong about the `stackoverflow`; my bad. – RobIII Jun 04 '18 at 09:05
  • See also [Why the function called by setTimeout has no callstack limit?](https://stackoverflow.com/q/24631041/1048572), [Why such recursion not getting stack-overflowed?](https://stackoverflow.com/q/56937740/1048572) and [Why does a function with setTimeout not lead to a stack overflow](https://stackoverflow.com/q/61986701/1048572) – Bergi Jan 17 '21 at 18:53

2 Answers2

6

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.

korona
  • 2,308
  • 1
  • 22
  • 37
0

Is this something that could lead to memory leaks?

-If the function FOO() runs to completion before the timeout calls it again then no. The stack should be cleared.

Is it better/clearer to still limit the number of calls to the function?

-Yes, since your timeout variable will eventually overflow and may cause unintended results.

Would other languages use such approach or are there different mindsets outside of JS world?

-Depends on how the timer functions works for the library/language you use. But this seems like a simple way and valid way to have an increasing timeout.