Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
How can a JavaScript class instance clear timers when it is dereferenced?

I have a situation like this:

class Thing {
  constructor() {
    this.timer = setInterval(() => console.log('Hi'), 1000);
  }
}

let a = new Thing();
// ... various stuff happens which takes less than 1s ...
a = undefined;

The problem is, the a instance of Thing continues to trigger the timer closure after a has been set to undefined:

Hi
Hi
Hi
Hi
Hi

Now I could have the parent scope call a method to tell the instance to stop the timer, but the parent doesn't actually know a timer is being used - it's an internal implementation detail of Thing.

How can Thing know it's been dereferenced so it can clean up and allow itself to be GCed?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use a FinalizationRegistry:

class Thing {
  constructor() {
    this.timer = setInterval(() => console.log('Hi'), 1000);
  }
}

let a = new Thing();

const registry = new FinalizationRegistry(timer => {
    clearInterval(timer);
    console.log('Cleared');
});

registry.register(a, a.timer);

a = undefined;

Note that it might take some time before the object is garbage collected. In my tests of the above code, the interval ran about 5-20 times before being eventually cleared.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda