使用数组跟踪多个 setTimeouts 的逻辑是什么

what is the logic of using an array to keep track of multiple setTimeouts

我刚刚浏览了 react-slick 的代码,遇到了以下代码:-

this.callbackTimers.push(
     setTimeout(() => this.setState({ animating }), 10)
);

在 componentWillUnmount 中,callbackTimers 是这样清除的:-

componentWillUnmount = () => {
    if (this.callbackTimers.length) {
      this.callbackTimers.forEach(timer => clearTimeout(timer));
      this.callbackTimers = [];
    }
};

使用数组释放内存的唯一目的是什么还是我在这里遗漏了什么?

为什么不直接调用 setTimeout:

setTimeout(() => this.setState({ animating }), 10)

而不是使用数组?我确实看到 callbackTimers 也在其他地方使用,但我不知道为什么除了释放内存之外还需要这个数组,这个数组还有其他用途吗?

可以找到有问题的行 HERE

clearTimeout() 函数只需要取消任何挂起的计时器。否则,你真的不需要调用clearTimeout()函数来清除内存。

在您问题的代码中,计时器在 componentWillUnmount 生命周期方法中被清除,以在组件即将卸载时取消任何挂起的计时器。这将阻止任何挂起计时器的回调函数中的任何代码在组件卸载后执行。