You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用FinalizationRegistry在对象销毁时清除类构造函数中的定时器?

JavaScript 中利用 FinalizationRegistry 实现对象回收时清理定时器的问题

问题代码与测试现象

我借助ChatGPT编写了如下代码,试图用FinalizationRegistry为类实现类似析构函数的逻辑,在对象被垃圾回收时清除定时器:

class Thing {
    #intervalId;
    #finalizationRegistry;
    constructor() {
        console.log('constructor()');
        let count = 0;
        this.#intervalId = setInterval(() => {
            console.log(`Test ${count++}`);
        }, 1000);

        this.#finalizationRegistry = new FinalizationRegistry(() => {
            this.#destructor();
        });
        this.#finalizationRegistry.register(this);
    }
    #destructor() {
        console.log('destructor()');
        clearInterval(this.#intervalId);
    }
}

(() => {
    const x = new Thing();
})();

但测试时console.log('destructor()');从未执行。我最初的代码用构造函数内的虚拟对象作为辅助值,赋值x = null时能触发析构,但代码存在错误。

如何测试这段代码是否能调用析构函数?

上述代码是用FinalizationRegistry清除setInterval的最小示例,我不确定它是否有效,请问有没有方法测试这段代码是否能触发析构函数?

实际需求与核心疑问

我的实际需求是实现一个Cache类,其中需要运行如下定时器逻辑:

this.#intervalId = setInterval(() => {
   this.#prune();
}, 1000);

我希望在对象无法再被访问时自动清除该定时器,就像上述示例代码那样。请问:

  • 能否在类构造函数中创建引用this的定时器,并在对象被垃圾回收时清除它?
  • 当定时器持有this引用时,对象是否还能被垃圾回收?如果不能,有没有解决方案?

内容的提问来源于stack exchange,提问作者jcubic

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:06:08