Frame-Based Media Player in JavaScript
Data Structure DesignModel answerLast 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 advancementpause()— halt playbackseek(frameIndex)— jump to a specific framesetFPS(fps)— change the playback ratecurrentFrame()— return the current frame indexisPlaying()— return whether playback is active
Requirements:
- Use timer primitives (
setTimeoutorsetInterval) 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
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Drift-Correcting Frame Player
Core Strategy
The fundamental challenge is maintaining accurate timing over extended playback. A naive approach—incrementing the frame index on each timer callback—accumulates error because callbacks are never perfectly punctual. The solution is to compute frame position as a function of elapsed wall-clock time.
Time-based positioning: When playback begins, record a reference pair (referenceTime, referenceFrame). On each timer tick, calculate which frame should be displayed:
targetFrame = referenceFrame + floor((currentTime - referenceTime) * fps / 1000)
This formula makes the player self-correcting: if a callback arrives late, we jump to the correct frame rather than staying one behind. Dropped frames are skipped automatically without iteration.
Timer Comparison
setInterval:
- Fixed periodic callbacks
- Changing FPS requires tearing down and recreating the interval
- Callbacks queue up if they take longer than the interval
- Higher risk of duplicate intervals if not carefully managed
Recursive setTimeout:
- Each delay can be computed individually
- FPS changes take effect immediately on the next tick
- Requires anchor-based correction to avoid drift
- Natural single-timer guarantee if structured correctly
requestAnimationFrame:
- Synchronized with display refresh (typically 60 Hz)
- Excellent for smooth visual updates
- Pauses automatically in background tabs
- Not suitable for arbitrary FPS rates without additional logic
- Best used in combination: rAF for rendering, time-based logic for frame selection
Recommendation: Recursive setTimeout with drift correction provides the most control for variable FPS requirements while remaining straightforward.
Preventing Drift
Each timer schedules the next frame boundary, not a fixed delay:
const frameInterval = 1000 / fps;
const elapsed = now() - referenceTime;
const nextBoundary = (Math.floor(elapsed / frameInterval) + 1) * frameInterval;
const delay = nextBoundary - elapsed;
setTimeout(tick, delay);
This ensures each frame aligns to its theoretical timestamp regardless of prior callback latency.
Preventing Overlapping Timers
Maintain a single timerId variable. Before scheduling:
- Clear any existing timer
- Set the new timer
- Store its ID
Every code path that modifies playback state (play, pause, seek, setFPS) goes through the same clearing mechanism.
Edge Case Handling
Invalid frame indices:
- Non-integer or NaN: throw immediately
- Out of bounds: clamp to valid range
[0, frameCount - 1] - Document this choice—some APIs throw on out-of-bounds, others clamp
Invalid FPS:
- Zero, negative, NaN, or Infinity: throw
RangeError
Seeking during playback:
- Render the target frame immediately
- Establish a new reference point
(now, targetFrame) - Reschedule so the next frame arrives after a full interval
End of sequence:
- If looping: wrap using modulo arithmetic
- If not looping: render final frame, stop playback, fire completion callback
Resuming from pause:
- Create a fresh reference point at current frame
- If paused at the end without looping, restart from frame 0
Redundant operations:
- Multiple
play()orpause()calls are idempotent
Background tabs:
- Attach a
visibilitychangelistener - When tab becomes visible, trigger an immediate tick to catch up
Implementation
function createFramePlayer(config) {
const {
frameCount,
fps: initialFPS = 30,
render,
loop = false,
onComplete = null,
} = config;
// Validation
if (!Number.isInteger(frameCount) || frameCount <= 0) {
throw new RangeError('frameCount must be a positive integer');
}
if (typeof render !== 'function') {
throw new TypeError('render must be a function');
}
let currentIndex = 0;
let fps = initialFPS;
let isActive = false;
let timerId = null;
let referenceTime = 0;
let referenceFrame = 0;
let isDestroyed = false;
function validateFPS(value) {
if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {
throw new RangeError('fps must be a positive finite number');
}
}
validateFPS(fps);
function clearTimer() {
if (timerId !== null) {
clearTimeout(timerId);
timerId = null;
}
}
function displayFrame(index) {
currentIndex = index;
render(index);
}
function recordReference() {
referenceTime = performance.now();
referenceFrame = currentIndex;
}
function scheduleNextFrame() {
clearTimer();
const frameMs = 1000 / fps;
const elapsed = performance.now() - referenceTime;
const framesElapsed = Math.floor(elapsed / frameMs);
const nextFrameTime = (framesElapsed + 1) * frameMs;
const delay = Math.max(0, nextFrameTime - elapsed);
timerId = setTimeout(advanceFrame, delay);
}
function advanceFrame() {
timerId = null;
if (!isActive || isDestroyed) return;
const frameMs = 1000 / fps;
const elapsed = performance.now() - referenceTime;
const framesDelta = Math.floor(elapsed / frameMs);
let targetIndex = referenceFrame + framesDelta;
if (targetIndex >= frameCount) {
if (loop) {
targetIndex = targetIndex % frameCount;
} else {
displayFrame(frameCount - 1);
isActive = false;
if (onComplete) onComplete();
return;
}
}
if (targetIndex !== currentIndex) {
displayFrame(targetIndex);
}
scheduleNextFrame();
}
function handleVisibilityChange() {
if (isActive && document.visibilityState === 'visible') {
advanceFrame();
}
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', handleVisibilityChange);
}
displayFrame(0);
return Object.freeze({
play() {
if (isDestroyed || isActive) return;
if (!loop && currentIndex === frameCount - 1) {
displayFrame(0);
}
isActive = true;
recordReference();
scheduleNextFrame();
},
pause() {
if (!isActive) return;
isActive = false;
clearTimer();
},
seek(frameIndex) {
if (isDestroyed) return;
if (!Number.isInteger(frameIndex)) {
throw new RangeError('frameIndex must be an integer');
}
const clampedIndex = Math.max(0, Math.min(frameIndex, frameCount - 1));
displayFrame(clampedIndex);
if (isActive) {
recordReference();
scheduleNextFrame();
}
},
setFPS(newFPS) {
validateFPS(newFPS);
fps = newFPS;
if (isActive) {
recordReference();
scheduleNextFrame();
}
},
currentFrame() {
return currentIndex;
},
isPlaying() {
return isActive;
},
destroy() {
if (isDestroyed) return;
isDestroyed = true;
clearTimer();
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', handleVisibilityChange);
}
},
});
}
Complexity
- Time: O(1) per operation. Frame skipping is computed arithmetically, not via iteration.
- Space: O(1) for the controller state. Frame storage is external.
Testing Strategy
// Basic playback
const frames = [];
const player = createFramePlayer({
frameCount: 100,
fps: 10,
render: (i) => frames.push(i),
});
player.play();
// After 1 second, expect frames near [0, 1, 2, ..., 10]
// Seek during playback
player.seek(50);
// Expect immediate render of frame 50, then 51, 52...
// FPS change
player.setFPS(20);
// Subsequent frames arrive twice as fast
// Pause and resume
player.pause();
const pausedAt = player.currentFrame();
player.play();
// Continue from pausedAt
// End behavior
player.seek(99);
player.play();
// Without loop: stops at 99, fires onComplete
Common mistakes to avoid: accumulating frame deltas instead of computing from elapsed time, forgetting to clear timers before creating new ones, not handling the paused-at-end state, and failing to clean up event listeners.