Javascript 定时器在递归函数中使用时会被释放吗?

Are Javascript timers released when using them in recursive function?

我看到下面的代码,其中递归调用 setTimeout 直到 window.value 不可为空:

const process = () => {
  return new Promise(resolve => {
    (function checkScriptParsed(self) {
      self.timer = window.setTimeout(() => {
        if (window.value) {
          clearTimeout(self.timer);
          resolve();
        } else {
          checkScriptParsed(self);
        }
      }, 50);
    })({});
  });
};

我的问题是,如果 window.value 在 00:00:00 后 50 毫秒变得不可为空并且每毫秒生成一个计时器,那么在 [= 之后的 50 毫秒是否会有 49 个活动计时器 运行 19=]?

不,一次只有一个计时器处于活动状态,因为 setTimeout 是一次性的:与 setInterval 不同的是,它不会再次启动。事实上,这一行

clearTimeout(self.timer);

是垃圾,因为调用时计时器已经完成,不需要清除。

代码似乎是类似于

的过于复杂的版本
const process = () => {
  return new Promise(resolve => {
    const timer = setInterval( () => {
      if (window.value) {
        clearInterval(timer);
        resolve();
      } 
     }, 50);
  });
};

即便如此,异步加载脚本上的 load 事件处理程序可能是检测脚本是否已被解析的更好方法。