Counter

How to make a counter in pure javascript. The input returns the total amount of seconds since the timer started.

by hambern

HTML

<input name="timer" type="hidden" data-timer-input>
<span data-timer-display></span>

JavaScript

const timer = {
  interval: null,
  startTime: null,

  start: function() {
    const displayElement = document.querySelector('[data-timer-display]');
    const inputElement = document.querySelector('[data-timer-input]');
    this.startTime = new Date();

    this.interval = setInterval(() => {
      const elapsed = new Date() - this.startTime;
      const minutes = Math.floor(elapsed / 60000);
      const seconds = Math.floor((elapsed % 60000) / 1000);
      const formattedTime = `${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;

      displayElement.innerHTML = formattedTime;
      inputElement.value = Math.floor(elapsed / 1000);
    }, 1000);
  },

  stop: function() {
    clearInterval(this.interval);
    this.interval = null;
  }
};

timer.start();