A. Wolff
A. Wolff

Reputation: 74420

strange behaviour in recursive function

Could someone explain why the second function doesn't bring us a stack overflow?

//stack overflow on call
function test1() {
    test1();
}
//no stack overflow, nor beer
function test2() {
    setTimeout(test2, -500); //back to the future
}

Upvotes: 1

Views: 84

Answers (1)

I Hate Lazy
I Hate Lazy

Reputation: 48761

Because it's not recursive. The test2 function is able to return, and some time later another invocation is scheduled by setTimeout via the anonymous function that was created.

Obviously, you can't go back in time. setTimeout has a minimum duration.


FWIW, the anonymous function is unnecessary. You could do setTimeout(test2, -500).

Upvotes: 8

Related Questions