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?

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):
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 :)