The purpose
When performing a process triggered by an event in JavaScript, addEventListener
is commonly used. However, there are times when you only want the process to execute once (e.g., initialization after a ‘ready’ event).
While removeEventListener
could be used, it’s cumbersome because you have to set up an identical listener to remove it (which can lead to maintenance errors).
This article will introduce a method to perform a process only once without using removeEventListener
.
Implementation
Normally, addEventListener
is likely written as follows:
element.addEventListener(event, callback);
// example
// element.addEventListener("click", ()=>{console.log("clicked")});
With this implementation, the callback
will be executed every time the event occurs. We will modify this implementation as follows:
element.addEventListener(event, callback, {once: true});
If the third argument of the pre-modification version was true
It would be as follows:
Before
element.addEventListener(event, callback, true);
After
element.addEventListener(event, callback, {once: true, capture :true});
Result
The listener set with addEventListener
will now execute only once.
Refference

comment