#679 Resumable Interval

medium
javascript
timers
async

Your quiz app autosaves every 30 seconds and shows a countdown to the next save. When the student switches to another tab, you pause the timer. With a plain setInterval you can only clear it and start a new one, so a student who left 25 seconds into a period comes back and waits a full 30 seconds again. The countdown jumps and the save drifts. You want an interval that remembers where it was: after a pause, it waits only for the time that was left, then goes back to the normal rhythm.

Write createResumableInterval(callback, delay, ...args). It returns an object with:

  • start(): starts the interval, or resumes it after a pause.
  • pause(): stops the calls for now and remembers how much of the current period is left.
  • stop(): ends the interval for good.
  • state: one of "idle", "running", "paused" or "stopped".
const autosave = createResumableInterval(saveDraft, 30_000, quizId);

autosave.start();   // saveDraft(quizId) at 30s, 60s, 90s, ...

// 25s into a period the student leaves the tab
autosave.pause();

// minutes later they come back
autosave.start();   // next save after 5s, then every 30s again

Rules:

  • delay must be a finite number that is 0 or more. Otherwise createResumableInterval throws a RangeError.
  • Creating the interval does not start it. The state is "idle" until start() is called.
  • The first call happens delay ms after the first start(), not right away. Each call gets the extra args that were passed in.
  • pause() stops the calls and keeps the time left in the current period. The next start() waits that long for the next call, then calls every delay ms again.
  • The time left adds up across several pauses. Pausing 40 ms into a 100 ms period, resuming, and pausing again 40 ms later leaves 20 ms.
  • start() while running does nothing. It must not add a second interval or reset the timing.
  • pause() while idle, paused or stopped does nothing.
  • stop() works from any state. After it, start() and pause() do nothing and the state stays "stopped".
  • The callback may call pause() or stop() on its own interval. If it pauses, a full delay is left.
  • A callback that throws does not end the interval. The next call still happens on time.
  • Each interval keeps its own timing.
const timer = createResumableInterval(tick, 100);

timer.start();   // state: "running"
// 130ms later: tick called once, 30ms into the second period
timer.pause();   // state: "paused", 70ms left
timer.pause();   // already paused, still 70ms left
timer.start();   // tick at +70ms, then every 100ms
timer.stop();    // state: "stopped"
timer.start();   // nothing happens