«   Previous tip Next tip   »

JavaScript: Automatically remove an event listener after it has executed

Last updated: 14th March 2023

You 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.

«   Previous tip Next tip   »

Sign up to receive a developer tip, in the form of a gif, in your inbox each week