You can create a function that is named only in the scope in which it is executed, and after executing the action of addEventListener
, call removeEventListener
to remove it.
So:
var button = document.querySelector('#button');
var i = 0;
button.addEventListener('click', function click(e) {
i++;
console.log("Essa função foi chamada %d vez", i);
button.removeEventListener('click', click);
});
<button id="button">Clica aí</button>
In this way, unlike using a variable indicating whether the button was clicked or not, the listener of that event will be removed, which may be interesting for performance gain, since you do not need to have a listener since the same will no longer do anything.
Addendum:
If you're using jQuery, you can use the one
method to simplify the work:
$('#button').one('click', function (e) {
// Executa somente essa vez, não mais que isso
});
It would be cool to have a look at these questions: