← JavaScript Coding

Event Emitter with Once

mediumeventsclassescallbacks
Asked at
GitHub
LinkedIn
Meta
Netflix
Vercel
GitHub, LinkedIn, Meta, Netflix, Vercel

Problem statement

Implement an EventEmitter class with on, once, off, and emit.

Requirements

  • on(event, callback) subscribes and returns an unsubscribe function.
  • once(event, callback) subscribes for only the next emit.
  • off(event, callback) removes a callback.
  • emit(event, ...args) calls listeners in subscription order.
  • Removing a listener during emit should not skip later listeners from the same emit cycle.

Requirements & constraints

  • →Listeners should run in subscription order.
  • →`off` should work for both `on` and `once` callbacks.
  • →Return an unsubscribe function from `on` and `once`.

How to approach Event Emitter with Once

The strategy an interviewer expects you to reach for.

Event emitters with once are pub/sub plus self-removing listeners — analytics “fire exactly one time” hooks. Naive move Register with on and remove after emit inside the callback. If emit is re-entrant or the callback throws, removal can be skipped or order gets weird. Where it breaks once must unsubscribe before invoking so recursive emits do not re-enter. Duplicate function references should not double-register if you use a Set. The fix Map event → Set of listeners. once wraps the callback, removes the wrapper first, then calls through. Snapshot listeners when emitting so mutations mid-emit are safe. Remember: once removes itself before calling; emit from a snapshot. Say this in the interview: I'd store listeners in a Set per event, wrap once-handlers so they unsubscribe before running, and emit over a copied list.

Premium

The full solution is part of HelloFrontend Pro

The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.

  • Runnable editor with the hidden test suite
  • Progressive hints that unlock as you get stuck
  • Senior-level reference solution with a line-by-line walkthrough
Unlock the full solution →

Already a member? Log in to open the workspace.

More JS Coding questions

View all JS Coding →
JS CodingMedium

5. Throttle

JS CodingMedium

13. Deep Clone

JS CodingMedium

14. Event Emitter

JS CodingEasy

66. Promise Methods

JS CodingEasy

19. Memoize I

JS CodingMedium

86. API Retry

Explore related prep hubs

  • All JavaScript coding
  • JavaScript interview questions
  • JS polyfill interview questions
  • Debounce & throttle questions
  • React interview hub
  • GitHub interview
  • LinkedIn interview
  • Meta interview
  • Netflix interview
  • Vercel interview