Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

211
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!