It’s super cool that addEventListener lets us have multiple handlers for the same event, like Hariseldon mentioned in the quiz discussion (JS Quiz: Easy: Simplest DOM event listener - #2 by HariSeldon). That’s a huge upgrade from the old onclick days! I was playing around with it and thought, what if we want to temporarily listen for something? Or maybe just once? removeEventListener is great for cleanup, but once makes it even cleaner for single-shot actions. It’s so handy for things like intro animations or one-time user prompts.
Here’s a quick example where a button changes color only on its first click, then stops listening:
<button id="myTemporaryButton">Click me once!</button>
const myTemporaryButton = document.getElementById('myTemporaryButton');
const handleClickOnce = () => {
myTemporaryButton.style.backgroundColor = 'lightcoral';
myTemporaryButton.textContent = 'Clicked!';
console.log('This handler ran only once!');
};
myTemporaryButton.addEventListener('click', handleClickOnce, { once: true });
// Try clicking multiple times, it only fires the first time.
Yeah, once is one of those little options I reach for all the time now. It’s perfect for exactly the kind of thing you showed - a first-click intro, a one-time prompt, something you never want firing twice. The one catch that caught me out early on: once removes the listener even if the handler throws. So if something goes wrong inside that first run, you don’t get a second chance - the listener is already gone. For a color-change button that’s no big deal, but for anything where a failed first attempt should be retryable, I tend to leave once off and remove it manually only after it actually succeeds.
There’s another interesting edge case with once when the event handler is async.
The listener gets removed as soon as the event fires, not when the async operation finishes successfully. So if you’re using it for something like submitting a request, a rejected promise still leaves the button without its listener.
For that kind of action, I’d usually keep the listener attached and use a simple pending flag to prevent duplicate clicks while the request is running. Then reset the flag in finally so the user can retry if something fails.
I think once: true is great when you genuinely want only one attempt, but it’s worth distinguishing that from an action you want to complete successfully once. Those sound similar, but behave quite differently when errors happen.