7oso
7oso

Reputation: 283

Will this code cause a stack overflow? Javascript setTimeout()

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();
}

Upvotes: 1

Views: 91

Answers (1)

voithos
voithos

Reputation: 70602

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).

Upvotes: 3

Related Questions