I have similar problem in my main project. Down below I shown my problem to the simplified way. I know why my code in executing couple times, the question is how to repair this.
HTML Code:
<body>
<button id="btn">CLICK ME</button>
<script src="index.js" defer></script>
</body>
Javascript:
const btn = document.getElementById("btn");
var number = 1;
function load() {
console.log(number);
btn.addEventListener('click', (e) => add(e))
};
function add(e) {
number = 1;
load();
e.stopPropation();
}
load();
And of course when I click the button first time everything is fine, but when I click second time, the button executes function two times, after third click four times and so on. I thought that e.stopPropation();
will solve the problem, but unfortunately is not.
Main Question: How to kill events which are doubled?
CodePudding user response:
here use this
const btn = document.getElementById("btn");
var number = 1;
function load() {
console.log(number);
btn.addEventListener("click", (e) => add(e));
}
function add(e) {
number = 1;
load();
e.stopImmediatePropagation();
}
load();