Search code examples
javascriptrecursionsettimeout

recursion with setTimeout flow anomaly


Please see the below code. I thought the '11111111' line would never be executed but it is. Can anyone please explain.

function outer() {
  function inner(dur) {
    console.log('in inner');

    setTimeout(() => {

      outer();
      console.log('11111111');

    }, dur);

  }
  console.log('in outer');
  inner(5000);
}

outer();

I expected an infinite loop. That happened. But I never expected the '11111111' to execute.


Solution

  • setTimeout() is an asynchronous function. It schedules its callback function to be called later, then returns immediately without waiting for it. So anything after setTimeout() will be executed immediately, without waiting for the timeout.

    So inner() returns immediately after it's called, and then outer() returns immediately. Sometime later (after dur milliseconds), the callback function is invoked. This isn't really recursive, because outer() and inner() have already returned. It's a new top-level call from the event loop.

    In the callback, we execute outer() again. As above, it calls inner() again, which calls setTimeout() and returns, and then it also returns. Then console.log('11111111') is executed. dur milliseconds later this all will be repeated.