KatInterview

Frame-Based Media Player in JavaScript

Data Structure DesignModel answer
MediumModel answerData Structure Designjavascripttimersclosures

Last updated

Build a JavaScript controller for frame-by-frame playback with play, pause, seek, and configurable FPS, handling timer accuracy and state management.

Design and implement a controller for a frame-based media player in JavaScript. Your implementation should support the following functionality:

  • Navigation: Jump to any frame by its index
  • Playback: Start and stop automatic frame advancement at a specified frames-per-second rate
  • Configuration: Allow the playback speed to be adjusted dynamically

Your controller must expose these methods:

  • play() — begin automatic frame advancement
  • pause() — halt playback
  • seek(frameIndex) — jump to a specific frame
  • setFPS(fps) — change the playback rate
  • currentFrame() — return the current frame index
  • isPlaying() — return whether playback is active

Requirements:

  • Use timer primitives (setTimeout or setInterval) to orchestrate frame timing
  • Prevent timer drift from accumulating over long playback sessions
  • Ensure only one timer can be active at any moment
  • Use closures to encapsulate internal state
  • Clean up all resources properly to avoid memory leaks

Discussion points:

  • Explain your approach to scheduling frames and preventing drift
  • Compare different timer strategies for this scenario
  • Describe how you handle boundary conditions: seeking during playback, invalid inputs, reaching the final frame, changing FPS mid-playback
  • Show how you would test key behaviors

Provide working code or detailed pseudocode with example usage.

Hints

Hint 1

Track a reference timestamp and frame when playback starts, then calculate the current frame from elapsed time rather than incrementing per callback

Hint 2

Clear any existing timer before scheduling a new one to prevent overlaps

Hint 3

When seeking or changing FPS during playback, establish a new reference point to keep timing accurate