To execute an event listener only once(JavaScript)

This article can be read in about 3 minutes.
PR

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.

PR

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});
PR

Result


The listener set with addEventListener will now execute only once.

PR

Refference

EventTarget: addEventListener() メソッド - Web API | MDN
addEventListener() は EventTarget インターフェイスのメソッドで、ターゲットに特定のイベントが配信されるたびに呼び出される関数を設定します。

comment

Copied title and URL