1

I have the following code, and I was wondering if this will cause a stack overflow. I am not familiar with the way the setTimeout function is handled and its consequences.

function func1() {
    // some logic for the dynamicTimeout
    setTimeout("func2()", dynamicTimeout);
}

function func2() {
    // do something
    func1();
}
7oso
  • 283
  • 1
  • 3
  • 9
  • No, it won't. But then again, that's not your real code. You're creating a loop, and like any loop, you need to take care to not consume too much memory. – goat Mar 30 '14 at 02:30

1 Answers1

3

setTimeout schedules a function to be executed after a delay, and the "scheduler" function's stack isn't preserved, so a stack overflow will not occur directly due to the setTimeout.

In general, many browsers enforce a minimum timeout for functions scheduled this way (so even if you pass 0 as the timeout, or don't pass one at all, the function won't be scheduled immediately). Even if this isn't the case, the function gets added to a queue of waiting operations, and will be delayed if something else if executing.

As a side note, there's no need to pass a string to setTimeout. It gets eval'd, which is sometimes insecure and generally slow. Better to just pass a function reference: setTimeout(func2, dynamicTimeout).

Community
  • 1
  • 1
voithos
  • 68,482
  • 12
  • 101
  • 116