DEV Community

XingYu Chen
XingYu Chen

Posted on Fully Autonomous

Caption Timing in JavaScript: Interval Boundaries, Progress, and NaN

The code behind this article comes from MakeShort, an online short-video tool I develop. While reviewing its caption renderer, I revisited interval boundaries and animation progress. This article explains those details with a standalone example.

Two small functions underpin several caption effects: deciding whether a caption is active, and calculating its animation progress. Word highlighting, caption transitions, and fades depend on these decisions.

The discussion starts with the current implementation. The defensive handling below is a proposed improvement, not a claim that it has shipped.

1. Who owns the boundary between adjacent captions?

Consider two captions, with all times in milliseconds:

Caption A: 1000 → 2000
Caption B: 2000 → 3000
Enter fullscreen mode Exit fullscreen mode

An inclusive test at both ends makes both captions active at exactly 2000 ms:

time >= start && time <= end
Enter fullscreen mode Exit fullscreen mode

For word highlighting, this can select two words at the boundary. Whether they visibly overlap depends on the rendering logic, but the timing rule itself is ambiguous.

The interval helper in the existing code uses a half-open interval:

time >= start && time < end
Enter fullscreen mode Exit fullscreen mode

Written as [start, end), it includes the start and excludes the end:

Current time Caption A Caption B
1999 ms Active Inactive
2000 ms Inactive Active
2001 ms Inactive Active

When intervals meet exactly, the boundary belongs only to the next caption.

This convention does not repair overlapping input. If A ends at 2100 ms and B starts at 2000 ms, both are still active during the overlap. Endpoint ownership and data validation are separate concerns.

2. Activity and animation progress answer different questions

Animation progress is commonly calculated as:

progress = (current - start) / (end - start)
Enter fullscreen mode Exit fullscreen mode

Then it is clamped to the range [0, 1]:

Math.max(0, Math.min(1, progress))
Enter fullscreen mode Exit fullscreen mode

For a caption running from 1000 to 2000 ms, progress is zero before the start, 0.5 at the midpoint, and one at and after the end.

Progress reaching one does not mean the caption is still active.

At 2000 ms, caption A can have progress equal to one while already being outside its active interval. Rendering should handle these decisions separately:

if (state.active) {
  drawCaption(state.progress);
}
Enter fullscreen mode Exit fullscreen mode

Testing whether clamped progress is between zero and one cannot determine visibility: every valid clamped result meets that condition.

3. Clamping does not remove NaN

The existing progress helper divides the elapsed time by the duration and clamps the result. Considered on its own, it does not guard against zero-duration intervals.

When the current time, start, and end are equal:

const progress = (1000 - 1000) / (1000 - 1000);
// NaN

Math.max(0, Math.min(1, progress));
// NaN
Enter fullscreen mode Exit fullscreen mode

Clamping is not a substitute for validating the input.

This does not establish that a production failure has occurred. Upstream validation might exclude these inputs, or actual data might never trigger the case. But a reusable helper should state what happens when the input is invalid.

4. A standalone implementation with an explicit failure policy

This example adopts four rules:

  • All times use milliseconds.
  • The end must be later than the start.
  • Non-finite values, zero-duration intervals, and reversed intervals are invalid.
  • Invalid input returns an inactive state with progress zero.
function sampleCue(timeMs, startMs, endMs) {
  const valid =
    [timeMs, startMs, endMs].every(Number.isFinite) &&
    endMs > startMs;

  if (!valid) {
    return {
      active: false,
      progress: 0,
    };
  }

  return {
    active: timeMs >= startMs && timeMs < endMs,
    progress: Math.max(
      0,
      Math.min(1, (timeMs - startMs) / (endMs - startMs))
    ),
  };
}
Enter fullscreen mode Exit fullscreen mode

Skipping invalid intervals is a policy choice. An editor could flag the offending caption for correction. An import pipeline could reject the record and explain why.

The important part is to choose a behavior before invalid values reach drawing code.

5. Test the boundaries, not just the midpoint

Checking that 1500 ms produces progress 0.5 will not catch most boundary errors. A useful test matrix also includes:

Case Expected result
Before the start Inactive, progress 0
Exactly at the start Active, progress 0
At the midpoint Active, progress 0.5
Exactly at the end Inactive, progress 1
After the end Inactive, progress 1
Equal start and end Inactive, progress 0
End before start Inactive, progress 0
NaN or Infinity in the inputs Inactive, progress 0

Test adjacent intervals explicitly as well:

console.assert(
  sampleCue(2000, 1000, 2000).active === false
);

console.assert(
  sampleCue(2000, 2000, 3000).active === true
);
Enter fullscreen mode Exit fullscreen mode

The standalone example passed 11 assertions covering these cases. Those assertions check the timing contract, not the entire video renderer. Preview testing still needs to account for frame sampling, media time units, and overlapping caption data.

6. Put the time unit in the interface

A correct formula can still produce incorrect timing if seconds and milliseconds are mixed.

The names timeMs, startMs, and endMs make the unit visible to callers. If a media interface supplies seconds, convert at the boundary into a millisecond-based caption timeline:

const timeMs = video.currentTime * 1000;
Enter fullscreen mode Exit fullscreen mode

This assumes the caption data actually uses milliseconds. Centralizing that conversion helps prevent one call path from converting twice while another forgets to convert at all.

Defining endpoint ownership, invalid-input behavior, and time units gives caption rendering a small, testable contract. That makes animation problems easier to investigate without guessing which part of the timeline a value belongs to.


AI disclosure: The prose and standalone example in this article were generated by an AI agent. The author reviewed the Chinese draft before requesting this English version. The agent checked the discussion against the existing code and ran 11 boundary assertions on the standalone example. This is not a claim of production validation or a shipped change.

Top comments (0)