Display text when timer reaches 0s, and add 0 before 1-9s

I want to display some text once the timer goes to 0:00, and when the timer is anywhere in between 1-9s, I want to display a 0 in front of the seconds, e.g. 1:04 instead of 1: 4. How would I do this?

const timeSpan = document.getElementById('timer');
var sec = 600 / 60;
const mins = sec;
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;


setInterval(() => {
  var currentTime = new Date().getTime();
  var distance = deadline - currentTime;
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);


  timeSpan.innerHTML = minutes + ':' + seconds;
  
}, 500)

You can:

  • Check minutes+seconds <= 0. If this is true, the count down reached 0. You can use this condition to output a custom string.
  • Get a the id of the timer from the call to setInterval and use it to stop the timer when the delay is zero.
  • Format the output by replacing single digits with double digits, using a regular expression. There are many other ways to do this.

const timeSpan = document.getElementById('timer');
const mins = 6 / 60; // For the demo I shortened the deadline
const now = new Date().getTime();
const deadline = mins * 60 * 1000 + now;

// Get the timer identifier
let timer = setInterval(() => {
  var currentTime = new Date().getTime();
  var distance = deadline - currentTime;
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  if (minutes+seconds <= 0) { // The delay is 0
      timeSpan.innerHTML = "You can claim points";
      clearInterval(timer); // Stop the timer
  } else {
      // Replace single digits with double digits
      timeSpan.innerHTML = (minutes + ':' + seconds).replace(/\b\d\b/g, "0$&");
  }
}, 500);
<span id="timer"></span>