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

202
Visualizações
Why do memory leaks occur when executing an event in JavaScript?

I have in my html a button with an id called "btn".

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Index</title>
    </head>

    <body>
        <button id="btn">Click!!!</button>
        <script src="./script.js"></script>
    </body>
</html>

The purpose is that each time it is pressed it will show or hide an image,

When click, an image is created from a template, its content is extracted and inserted into the DOM after the button and template is set to null, when the button is pressed again, it checks if the image It is already in the dom, if it is, it removes it and the reference sets it to null, this is the script.js:

const btn = document.getElementById('btn');

btn.addEventListener('click', () => {
    let img = document.getElementById('img');

    if (!img) {
        let template = document.createElement('template');
        template.innerHTML = '<img id="img" src="./img.jpg" alt="Image"/>';

        btn.after(template.content);
        template = null;
    } else {
        img.remove();
        img = null;
    }
});

When the event is triggered, the memory grows more and more, it should not be increasing, it should remain more or less constant, since, are the references removed once the scope of the function ends? Or not? enter image description here

After waiting approximately 1 to 2 minutes, the memory recently decreases, but still does not return to the initial value (that is, approximately 16,000 K, although the image is not in memory and not in the DOM):

enter image description here

what is happening? Should variables be automatically removed from a scope when it ends? or are they not deleted at the exact moment the scope ended? Am I understanding something wrong? Hope you can help me understand :)

about 4 years ago · Juan Pablo Isaza
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