JavaScript: Automatically remove an event listener after it has executed
Last updated: 19th July 2020In your JavaScript code, you can automatically remove an event listener after it has executed. Here's the code:
el.addEventListener('click', console.log, {
once: true
})
Removing event listeners, assuming they're not needed anymore, with {once: true}
will improve performance, and help your web app feel more responsive.
As shown on MDN, the once
flag is defined as follows:
A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.
Browser support is great apart from Internet Explorer.