Does a recursive setTimeout cause a stack info mem

2019-08-22 16:25发布

问题:

This question already has an answer here:

  • Is it necessary to clearTimeout inside a recursively invoked timer? 1 answer
  • Why the function called by setTimeout has no callstack limit? 2 answers

I have the following scenario:

let func = () => {
  //...
  let id = setTimeout(() => {
    console.trace();
    clearTimeout(id);
    func();
  }, 2000);
}

func();

Although I read that clearing the timeout handle will release the memory for closures and the handler itself, I am still curious if there might be a possible leak in stack information. I put the console.trace() call on purpose and it looks like the stack information grows indefinitely. Isn't that a concern? I know that it is not on a recursive-like stack where we might get a stack size exception but I'm still concerned about the stack information that keeps growing.

回答1:

No. When func finishes execution, the stack unwinds.

If func would be recursive, the stack would look like:

   [init] -> func -> func -> func -> func -> func -> .... 

In your case however it is:

  [init] -> func -> setTimeout
       <----     <----

  [timer] -> func -> setTimeout
      <----      <----

  [timer] -> func -> setTimeout
      <----      <----

  ...