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>