Timer

A lightweight, drift-free timer library built for the browser — precise, pause-resumable, and easy to use.

Source code & documentation

Demo

Open the browser's console to watch emitted events.
Elapsed (ms):
Remaining (ms):

Source Code

Sample code to create and control a Timer instance with a duration of 60,000 milliseconds (1 minute).

<div>
  <button id="start" type="button">Start</button>
  <button id="stop" type="button">Stop</button>
  <button id="reset" type="button">Reset</button>
</div>

<div>
  Elapsed (ms): <code id="elapsed"></code>
  <br>
  Remaining (ms): <code id="remaining"></code>
  <br>
  <progress id="progress"></progress>
</div>

<script>
  const startBtn = document.getElementById('start');
  const stopBtn = document.getElementById('stop');
  const resetBtn = document.getElementById('reset');
  const elapsedEl = document.getElementById('elapsed');
  const remainingEl = document.getElementById('remaining');
  const progressEl = document.getElementById('progress');

  function render(timer) {
    const { remaining, elapsed } = timer.time();
    elapsedEl.textContent = elapsed.toFixed(2);
    remainingEl.textContent = remaining.toFixed(2);
    progressEl.max = elapsed + remaining;
    progressEl.value = elapsed;
  }

  function onTimerTick(evt) {
    render(evt.currentTarget);
  }

  const timer = new Timer({
    duration: 60_000,
    elapsed: 0
  }).on('tick', onTimerTick);

  startBtn.addEventListener('click', () => {
    timer.start()
  });

  stopBtn.addEventListener('click', () => {
    timer.stop()
  });

  resetBtn.addEventListener('click', () => {
    timer.reset();
    render(timer);
  });

  render(timer);
</script>

License

Licensed under the The MIT License (MIT)