我如何知道是否有对给定实例的引用?



我正在构建一个队列,如果没有对队列实例的引用,我想避免执行任何任务。

我已经尝试了WeakRef,但可能永远不会工作。

const queue = () => {
const enqueue = () => {
console.log("enqueue");
setTimeout(() => {
if (instanceRef.deref()) {
console.log("the queue is still referenced so perform task");
}
});
};
const instance = { enqueue };
const instanceRef = new WeakRef(instance);
return instance;
};
b = queue();
b.enqueue();
b = null;
console.log("b is set to null so there are no references to the instance");

另一种方法是在队列仍然存在的情况下检入任务,但这种方法不太优雅。

不能依赖WeakRef#deref()来知道是否还有对目标对象的(强)引用。它仅仅指示垃圾收集器是否销毁了对象并回收了它的内存。这可能会在很久以后发生,也可能永远不会发生。

你想要的东西有点奇怪。您想要通过将null赋值给先前已经启动超时函数的变量来神奇地停止超时函数。

你想要的是有一个停止超时函数的方法。调用setTimeout返回一个处理程序。存储此处理程序并调用内置方法

clearTimeout(handler)

相关内容

最新更新