What if your event code could magically run just once without you writing extra checks?
Why Once listeners in Node.js? - Purpose & Use Cases
Imagine you want to run a piece of code only once when a button is clicked or a file is loaded, but you have to manually track if it already ran.
Manually tracking if an event happened before is tricky and error-prone. You might forget to reset flags or accidentally run the code multiple times, causing bugs or wasted resources.
Once listeners automatically run your code only the first time an event happens, then remove themselves. This keeps your code clean and reliable without extra checks.
let ran = false; eventEmitter.on('data', () => { if (!ran) { ran = true; console.log('Run once'); } });
eventEmitter.once('data', () => { console.log('Run once'); });
You can easily handle one-time events like setup, initialization, or cleanup without extra code to track execution.
When a server starts, you want to log a welcome message only once, no matter how many connections come in. Using a once listener makes this simple and safe.
Manual event tracking is complex and error-prone.
Once listeners run code only once and then remove themselves automatically.
This leads to cleaner, safer, and easier event handling.