Reputation: 197
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?
Upvotes: 2
Views: 789
Reputation: 36610
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
Upvotes: 1
Reputation: 1521
when your logA()
function is called for the first time then if
block is executed as expected. setTimeout(logA, 100);
is called for the first time.
In Javascript setTimeout()
runs asynchronously and therefore it will wait in stack for 100ms and the next statement which is console.log("after set timeout");
gets executed. After this logA function from first timeout gets executed which triggers one more timeout and so on.
So your output is as expected:
1
"after set timeout"
2
3
4
5
6
7
8
9
10
Upvotes: 1
Reputation: 4116
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");
Upvotes: 3