1

For example, if I run the following code in the browser and record the performance, after 10 clicks Chrome Dev Tools shows 21 listeners (see screenshot below), even though each listener is theoretically being removed before another is added.

And why are there 21 listeners after 10 clicks? That would suggest that there was one listener upon page load (correct) and that 2 listeners are added on each click, even though I am using e.stopPropagation(). Why is that?

My concern is how to spot memory leaks in my code if I am adding and removing a lot of elements and event listeners within a web app.

<div id="container"></div>

<script>
function addListener(){
    let container = document.getElementById("container");
    container.addEventListener("click", clickHandler, false);
}
function clickHandler(e){
    e.stopPropagation();
    let container = document.getElementById("container");
    container.removeEventListener("click", clickHandler, false);
    console.log("clicked"); 
    addListener();
}

addListener();
</script>

enter image description here

  • 1
    Garbage collection doesn't run immediately, it may take seconds or minutes to kick in depending on memory pressure. If this code is real then what is the purpose of re-adding the same listener on the same element? If this is an approximation of the real code, maybe you oversimplified it and now it doesn't reflect what actually happens. Click the trashcan icon and do a short recording: you should see the numbers go down. – wOxxOm Apr 03 '20 at 16:09
  • Hi wOxxOm, thanks for your comment. Yes, this is a piece of code I wrote to demonstrate the issue. It is pointless code except to demonstrate what I mean in my question. The actual code I was writing was far too long and not very clear for adding to stackoverflow. – DigitalDoughnut Apr 03 '20 at 16:15
  • 1
    Maybe this [question](https://stackoverflow.com/questions/11455515/how-to-check-whether-dynamically-attached-event-listener-exists-or-not) will help you with the goal. – EternalHour Apr 03 '20 at 17:07
  • wOxxOm, thanks, I did as you said - using the trash can - and the number did decrease back to one. I will run the same test on my original code. Thank you. Any idea why 2 event listeners were originally added for each click? – DigitalDoughnut Apr 03 '20 at 17:13
  • Thanks EternalHour, I had a look at that question before posting mine, but I will definitely revisit it and the links on it, as it will help my overall understanding of event listeners. Thanks for adding it. – DigitalDoughnut Apr 03 '20 at 17:32

0 Answers0