Performance: EventEmitter class
This affects how efficiently events are handled and how quickly the application responds to user or system actions.
Jump into concepts and practice - no test required
const EventEmitter = require('events'); const emitter = new EventEmitter(); for(let i = 0; i < 1000; i++) { emitter.on('data', () => { setImmediate(() => { // heavy task deferred asynchronously for(let j = 0; j < 1e6; j++) {} }); }); } emitter.emit('data');
const EventEmitter = require('events'); const emitter = new EventEmitter(); for(let i = 0; i < 1000; i++) { emitter.on('data', () => { // heavy synchronous task for(let j = 0; j < 1e6; j++) {} }); } emitter.emit('data');
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous listeners in EventEmitter | N/A | N/A | N/A | [X] Bad |
| Asynchronous deferred listeners in EventEmitter | N/A | N/A | N/A | [OK] Good |
EventEmitter class in Node.js?data using an EventEmitter instance called emitter?on method is used to register a callback to listen for a named event.emit sends events, not listens. listen and addEvent are not valid EventEmitter methods.const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', name => {
console.log(`Hello, ${name}!`);
});
emitter.emit('greet', 'Alice');emit('greet', 'Alice') runs, it calls the listener with 'Alice', printing "Hello, Alice!".const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.emit('start');
emitter.on('start', () => {
console.log('Started');
});ping is emitted and logs the count each time. Which code correctly implements this?