Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

140
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda