once
- Node.js course
- Intermediate
- Lesson 3/116
- 5 min
Learn one-time listeners with .once.
The once method
The once method registers a listener just like on; the difference is the listener is called only once, then automatically removed. Signature: emitter.once(eventName, listener).
This is useful for setup or first-use scenarios. Example: emitter.once("ready", () => console.log("First setup done"));. Even if emit("ready") is called three times, the message prints only once. Internally once uses on and removes the listener itself, so you do not need to remove it manually for one-time listeners.
once vs on
A listener added with on is called every time the event fires. A listener added with once is called only on the first fire; later fires ignore it.
Both methods share the same listener list; the once entry is specially marked. You can check active listeners with emitter.listenerCount(eventName). After the first emit, the once listener drops from the count; the on listener stays. This distinction is practical for one-time jobs like cache filling or first connection.
Practice Add a one-time listener
Create an emitter instance. Add a listener with once for the "ping" event that prints "Ping received". Call emit("ping") twice. The message should appear only once.
Starter code
// Create an emitter instance
// write here
// Add a one-time listener for the "ping" event
// write here
// Fire the "ping" event twice
// write hereSample solution
const { EventEmitter } = require("events");
const emitter = new EventEmitter();
emitter.once("ping", () => console.log("Ping received"));
emitter.emit("ping");
emitter.emit("ping");Expected output
Ping alındı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each method to its behavior
| Term | Meaning |
|---|---|
once |
One-time listener |
on |
Called every time |
emit |
Fires the event |
removeListener |
Removes a listener |
2 Complete the once call
emitter.____("once-event", handler);
emitter.once("once-event", handler);
Explanation: once registers a one-time listener.
3 What is the key difference between once and on?
emitter.once("x", fn) vs emitter.on("x", fn)- once runs faster
- once only listens to numeric events
- once calls the listener only once, then removes it Correct answer
- once never calls the event
Explanation: once calls the listener once, then removes it.