Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does setTimeout prevent potential stackoverflow

An example :

var list = readHugeList();

var nextListItem = function() {
    var item = list.pop();

    if (item) {
        setTimeout( nextListItem, 0);
        // ^^^^^^^^ this line
    }
};

How does use of setTimeout prevent potential stackoverflow here? I understand concept of event queue as well as stack, but I'm having difficulty connecting the two.

like image 650
Abhinav Gauniyal Avatar asked Mar 13 '23 02:03

Abhinav Gauniyal


1 Answers

Set timeout would not cause stack overflow, because it is asynchronous. It will just put the callback to the event queue and not block the execution.

In the first case:

setTimeout just puts the callback to event queue and the parent function exits after without busying the stack.
Even though the timeout is 0 ms, it will be called in the next event loop, thus not blocking the code in execution

var nextListItem = function() {
    var item = list.pop();

    if (item) {
         setTimeout( nextListItem, 0);
    }
};

In the second case:

Parent call the child function putting new entry into stack, even though the parents is not cleared from the stack.
Eventually more recursive calls would blow the stack.

var nextListItem = function() {
        var item = list.pop();
    
        if (item) {        
           nextListItem();
        }
    };
like image 186
rishabh dev Avatar answered Mar 21 '23 06:03

rishabh dev