'Asynchronous behaviour. Recursive setTimeout doesn't complete

I don't get why my program doesn't finish the recursive function, before executing the next line of code.

console.clear();
var a = 1;

function logA() {
  if (a<11) {
    console.log(a);
    a++;
    setTimeout(logA, 100);
  }
  else {
    return;
  }
}

logA();
console.log("after set timeout");

sample: https://jsbin.com/moyanudeki/edit?js,console

What's going on in the stack?



Solution 1:[1]

There is no recursion here. setTimeout, as the name suggests, schedules a function for asynchronous execution, after the set amount of time (100ms, in this case) has expired. That doesn't stop the current batch of code from running.

I.e. logA() will return, the console prints "after set timeout", and then the VM waits for the 100ms to expire. When that happens, it executes logA(), which schedules itself again, and so on.

Just to be clear, this would be recursion:

console.clear();
var a = 1;

function logA() {
  if (a<11) {
    console.log(a);
    a++;
    logA();
  }
  else {
    return;
  }
}

logA();
console.log("after recursion");

Solution 2:[2]

Also maybe interesting for you in understanding how the stack behaves in javascript is understanding the event loop. In javascript first the stack is emptied and then are the asynchronous callbacks executed which are stacked up in the event queue.

In your example when we have the following code:

function test () {
  console.log('first log');
}

setTimeout(test, 0);

console.log('last log');

Now the function object test is passed in the event queue. After the stack is cleared this function gets executed.

But if you execute the function directy like this:

    function test () {
      console.log('first log');
    }

    setTimeout(test(), 0);

    console.log('last log');

Now the function code will be directly executed and the function will not end up in the event queue.

Hopefully this is helpful

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Máté Safranka
Solution 2 Willem van der Veen