JavaScript: Automatically remove an event listener after it has executed
Last updated: 14th March 2023You can automatically remove/cleanup your JavaScript event listeners after they have executed. Here's the code:
el.addEventListener("click", console.log, {
once: true,
});
When your event listeners are not needed anymore, you should remove them. Using {once: true}
will help improve performance, and help your web app feel more responsive.
As shown on MDN, the once
flag is defined as follows:
A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked. If not specified, defaults to false.