Does a recursive setTimeout cause a stack info mem

2019-08-22 15:48发布

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条回答
SAY GOODBYE
2楼-- · 2019-08-22 16:42

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
      <----      <----

  ...
查看更多
登录 后发表回答