Search code examples
javascriptloopssettimeoutstack-overflownested-loops

Is there will be any stack overflow error with setTimeout() in 1st function and closure 2nd function in javascript?


Is it possible that here will be stack overflow error after some time of work (after few hours of calculations)? Or another errors in long run here?

    var timerIdPrecalculationsTurns = null;

    function precalculationsInit() {
        if (!timerIdPrecalculationsTurns) {
            timerIdPrecalculationsTurns = setTimeout(function(){
                precalculationsInitClosure();
            }, 10);
        }
    }

    function precalculationsInitClosure() {
        // make some calculations for ~20ms ...
        // and then repeat in next iteration:
        timerIdPrecalculationsTurns = null;
        precalculationsInit();
    }

    // just start the loop
    precalculationsInit();

It is simplified version of code, I used. But it will tell about my problem, I hope.

There are some similar answers, but I am not sure if it is my situation also:

Will setTimeOut function in recursive function cause stack overflow?

JavaScript Closures and setTimeout


Solution

  • No, there won't be.

    Timers "set aside" the callback - they don't call them in the same execution stack as the one that's currently running (the one calling setTimeout). JS will continue executing the current script until the stack is empty before calling any callback set by a timer (or any completed async operation for that matter).

    In your case precalculationsInit would "schedule" precalculationsInitClosure, then finish executing, emptying the stack. Then at least 10ms later, JS would call the scheduled precalculationsInitClosure, do stuff, then call precalculationsInit and repeats the same procedure.

    Your stack would look like:

    (empty)
    pI (schedules pIC)
    (empty, JS looks for callbacks)
    pIC
    pIC -> pI (schedules pIC)
    pIC
    (empty, JS looks for callbacks)
    pIC
    pIC -> pI (schedules pIC)
    pIC
    (empty)
    ...and so on
    

    As you can see, because of this "scheduling"/"setting aside", the stack does not build up like in recursion:

    pI
    pI -> pIC
    pI -> pIC -> pI
    pI -> pIC -> pI -> pIC
    ...and so on