Search code examples
javascriptfunctionsettimeoutstack-overflow

Does Self-Invoke JavaScript function will causes stack overflow exception


Here I have a function that calls itself within a setTimeout callback function:

function myFunc(){

    // ... I'm doing my jobs here...

    setTimeout(function(){
        myFunc() //self invoke
    },1)
}

myFunc(); // start point

Does this code eventually will occurs stack overflow exception?
Thanks in advance.


Solution

  • No. Functions queued via setTimeout are only run once the main thread (or whatever thread is currently in progress) is complete - there are no nested calls / nested environments that could cause the overflow you're worried about. If you run this snippet, you'll never run into an error, for example:

    function myFunc(i) {
      if (i % 1000 === 0) console.log(i);
      setTimeout(function() {
        myFunc(++i)
      })
    }
    myFunc(0);

    The same sort of thing is true for functions that invoke promises that call themselves recursively via .then - it's perfectly safe.