CKTIS / JavaScript
One-shot event listeners with `once`
Use `{ once: true }` to make an event listener run at most once per registration. The registration is removed before its callback runs.
Version: Current web platform; runtime support varies
Syntax
target.addEventListener(type, listener);
target.addEventListener(type, listener, { once: true });
target.addEventListener(type, listener, useCapture);The EventTarget.addEventListener once option is a property of the options object passed as the third argument. With { once: true }, that registration can invoke its callback at most once. Omitting once means false. Passing a bare true as the third argument sets capture, not once.
The API removes the registration just before invoking the callback. A nested dispatchEvent() with a new event of the same type therefore cannot invoke that callback through the same registration. A thrown exception does not restore the registration. If no event reaches the callback, once alone does not remove the registration.
On the same target, calling addEventListener() again with the same event type, callback, and capture value leaves the existing registration unchanged, even if once differs. To change the setting, first use removeEventListener() with the matching type, callback, and capture value, then register again.
EventTarget is a DOM API supplied by the host environment, not part of ECMAScript 2024. Check support for the option in the runtime where the code will run.
Examples
{
const target = new EventTarget();
let calls = 0;
target.addEventListener("ready", () => {
calls += 1;
if (calls === 1) target.dispatchEvent(new Event("ready"));
}, { once: true });
target.dispatchEvent(new Event("ready"));
target.dispatchEvent(new Event("ready"));
console.log(`calls: ${calls}`);
}Result
calls: 1
The first dispatch invokes the callback. Neither the nested dispatch nor the subsequent dispatch invokes it again. The expected log is `calls: 1`.
Related lessons
- JavaScript · Lesson 39 · Advanced · Version: 4