setMaxListeners Caps The Listener Warning
setMaxListeners without targets raises or lowers the process-wide listener cap; overflows warn on stderr instead of throwing.
Code
import { EventEmitter, setMaxListeners } from 'node:events';
// Default cap is 10 listeners per event name per emitter
const plain = new EventEmitter();
console.log('default cap:', plain.getMaxListeners());
// Without targets, setMaxListeners changes the process-wide default
setMaxListeners(3);
console.log('after setMaxListeners(3):', new EventEmitter().getMaxListeners());
// Beyond the cap Node prints a MaxListenersExceededWarning to stderr
// instead of throwing — the listener still fires
let calls = 0;
const capped = new EventEmitter();
for (let i = 0; i < 4; i++) {
capped.on('tick', () => calls++);
}
capped.emit('tick');
console.log('attached:', capped.listenerCount('tick'), '| handled:', calls);Output
Captured from a sandboxed run of this snippet in the build pipeline.
default cap: 10
after setMaxListeners(3): 3
attached: 4 | handled: 4How the snippet works
for (let i = 0; i < 4; i++) is the loop that carries the per-item work. The import names the platform contact area: EventEmitter, setMaxListeners, all from node:events.
Top-level bindings plain, calls, capped hold the demo state — nothing sits inside a function scope.
Watch out for
- No install needed:
node:eventscomes with Node.js itself.
Applying it
The run emits 3 labeled sections — default cap:, after setMaxListeners(3):, attached: — one per step.
Statements that matter
capped.on('tick', () => calls++);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Do I need to install anything before running this?
- Nothing needs installing: `node:events` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.