Calculate the sum of two-digit numbers using a live timer in JavaScript!

Is there a way to include leading zeroes for single digits in a JavaScript live timer? Currently, my timer displays days, hours, minutes, and seconds but when the value is between 1-9 it only shows a single digit. I want it to display as 01, 02, etc.

For example, instead of displaying just "1" for days, I want it to show "01".

(function () {
  const second = 1000,
        minute = second * 60,
        hour = minute * 60,
        day = hour * 24;

  let event = "July 10, 2021 01:00:00",
      countDown = new Date(event).getTime(),
      x = setInterval(function() {    

        let now = new Date().getTime(),
            distance = countDown - now;

          document.getElementById("days").innerText = ('0' + Math.floor(distance / (day))).slice(-2),
          document.getElementById("hours").innerText = ('0' + Math.floor((distance % (day)) / (hour))).slice(-2),
          document.getElementById("minutes").innerText = ('0' + Math.floor((distance % (hour)) / (minute))).slice(-2),
          document.getElementById("seconds").innerText = ('0' + Math.floor((distance % (minute)) / second)).slice(-2);

        //do something later when date is reached
        if (distance < 0) {
          let headline = document.getElementById("headline"),
              countdown = document.getElementById("countdown"),
              content = document.getElementById("content");

         
          countdown.style.display = "none";
          content.style.display = "block";

          clearInterval(x);
        }
        //seconds
      }, 0)
  }());
.container {
  color: black;
  margin: 0 auto;
  text-align: center;
  font-family: "Nunito";
}

h1 {
  font-weight: normal;
  letter-spacing: .125rem;
  text-transform: uppercase;
}

li {
  display: inline-block;
  font-size: 1.5em;
  list-style-type: none;
  padding: 1em;
  
}

li span {
  display: block;
  font-size: 4.5rem;
}


@media all and (max-width: 768px) {
  h1 {
    font-size: 1.5rem;
  }
  
  li {
    font-size: 1.125rem;
    padding: .85rem;
  }
  
  li span {
    font-size: 3.375rem;
  }
}
<div class="container" style="position: absolute;">
  <div id="countdown">
    <ul style="margin-top: -30px">
      <li><span id="days"></span>days</li>
      <li><span id="hours"></span>hours</li>
      <li><span id="minutes"></span>mins</li>
      <li><span id="seconds"></span>secs</li>
    </ul>
      <script src="script.js"></script>
  </div>

Answer №1

String.prototype.padStart():

(function() {
  const second = 1000,
    minute = second * 60,
    hour = minute * 60,
    day = hour * 24;

  let event = "July 10, 2021 01:00:00",
    countDown = new Date(event).getTime(),
    x = setInterval(function() {

      let now = new Date().getTime(),
        distance = countDown - now;

      document.getElementById("days").innerText = String(Math.floor(distance / (day))).padStart(2, '0'),
        document.getElementById("hours").innerText = String(Math.floor((distance % (day)) / (hour))).padStart(2, '0'),
        document.getElementById("minutes").innerText = String(Math.floor((distance % (hour)) / (minute))).padStart(2, '0'),
        document.getElementById("seconds").innerText = String(Math.floor((distance % (minute)) / second)).padStart(2, '0');

      //do something later when date is reached
      if (distance < 0) {
        let headline = document.getElementById("headline"),
          countdown = document.getElementById("countdown"),
          content = document.getElementById("content");


        countdown.style.display = "none";
        content.style.display = "block';

        clearInterval(x);
      }
      //seconds
    }, 0)
}());
.container {
  color: black;
  margin: 0 auto;
  text-align: center;
  font-family: "Nunito";
}

h1 {
  font-weight: normal;
  letter-spacing: .125rem;
  text-transform: uppercase;
}

li {
  display: inline-block;
  font-size: 1.5em;
  list-style-type: none;
  padding: 1em;
}

li span {
  display: block;
  font-size: 4.5rem;
}

@media all and (max-width: 768px) {
  h1 {
    font-size: 1.5rem;
  }
  li {
    font-size: 1.125rem;
    padding: .85rem;
  }
  li span {
    font-size: 3.375rem;
  }
}
<div class="container" style="position: absolute;">
  <div id="countdown">
    <ul style="margin-top: -30px">
      <li><span id="days"></span>days</li>
      <li><span id="hours"></span>hours</li>
      <li><span id="minutes"></span>mins</li>
      <li><span id="seconds"></span>secs</li>
    </ul>
    <script src="script.js"></script>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Employing a one-time use variable that is asynchronously loaded via a React hook

Currently, I am exploring the functionalities of React's hooks, but I'm encountering a roadblock when it comes to integrating different use cases. The main goal is to create a hook called useNationsAsync that fetches a list of available nations ...

Optimize your texture loading process by dynamically swapping out low resolution textures with high resolution ones to enhance overall visual quality

In my current ThreeJS project, I have encountered an issue when trying to swap one texture with another. The problem arises when the UV's become completely distorted after the texture switch. Below is the snippet of code that showcases how I am attemp ...

Include an edit button with each row in an HTML table for seamless editing of the database

I am currently exploring php and seeking assistance with a project for my internship. I have successfully queried all records from the mysql database and displayed them in an html table. However, I now want to include an edit button in a separate column fo ...

The datetime-picker from Twitter Bootstrap is not accurately displayed within a modal

Utilizing the twitter bootstrap datetime-picker in conjunction with Ruby on Rails has been a seamless experience for me. However, I have encountered a small issue when displaying it within a modal at the bottom of the screen. HTML <div id="datetimePic ...

What is the method to integrate PHP with HTML code?

Apologies if this question has been asked before, but I have not found anyone with the same query as mine. I am new to HTML and PHP, and I am looking to enhance my skills by creating a registration form and storing all the data in a MySQL database using XA ...

Maintain the HTML font color when printing - Issue with IE settings, not the printer

I've been struggling with this issue all day. Initially, I thought it was a problem with the print settings, but then I realized that it's actually the "Print background colors and images" option in IE causing the trouble. Here is the last test ...

A blank page is appearing mysteriously, free of any errors

I have experience with ReactJs, but I am new to Redux. Currently, I am working on implementing an async action where I call an API and display the data received from it. Initially, when all the Redux components (actions, reducers, containers) were on a sin ...

How can you use jQuery to activate a specific tab?

I have 3 tabs with 3 different ids. $(document).ready(function() { $(function() { $( "#tabs" ).tabs(); }); $("#links > a").click(function() { var link = $(this).attr('href').substr(-1,1); console.log(link); $('#t ...

Guidelines for choosing and uploading a file using Ionic

Is there a way to upload a PDF file to a server using the $cordovaFileTransfer plugin? I currently have an input field like this: <input type="file" onchange="angular.element(this).scope().fileNameChanged(this)"> How can I retrieve the pathForFile ...

Guide for combining two geometries or meshes in three.js version r71

Encountering a problem when attempting to merge two geometries (or meshes) into one, as the previously used function in earlier versions of three.js is no longer available. In an effort to merge the <code>pendulum and ball, I implemented the follo ...

Rendering an Image File from Database Using React JS and Node JS

I am encountering a problem with displaying an image file from my mongodb database on my Profile and EditProfile component. The issue arises when I upload the file using the Editprofile component - it saves to the database successfully. However, when I try ...

Snowflake Javascript function for adding current date to table name

I've recently delved into the world of Snowflake and hit a roadblock with this issue: My goal is to duplicate a table named AB_USER to AB_USER_(current_date). Here's the code I've come up with in an attempt to achieve that: CREATE or repl ...

Exploring the Methods to Monitor Variables in Framework7 Store

Currently, I am in the process of developing my app and have opted to utilize the new built-in store system instead of relying on Vuex. I have a variable that undergoes frequent changes and previously used the following code when working with Vuex: store.w ...

When the page reloads, the firebase currentUser variable is found to be

Currently utilizing Firebase for authentication. Prior to making a request to the backend, I always ensure to request the idToken. service.interceptors.request.use(async request => { const token = await firebase.auth().currentUser.getIdToken(); i ...

When the input field is in debug mode and has a keydown event listener, the character fails to appear as intended

As a newcomer to javascript/html, I have an input with a keydown event listener. Surprisingly, everything seems to work fine when I try it out in the browser. I type a character and see that my javascript is executed, then I type another character and it w ...

Generating a single JSON record in React Native

Need help displaying a single JSON record from an API request on the screen. const [user, setUser] = useState(); const getUserData = async () => { // {headers: {Authorization: "Basic " + base64.encode(username + ":" + passwor ...

When properties remain unchanged, they do not hold the same value in a Firestore-triggered Cloud Function

Within my Firestore database, there is a collection named events consisting of documents with attributes such as begin, end, and title. The function in question is triggered when any changes occur within a document. The begin and end fields are both categ ...

Having Trouble with the Back Button Functionality

Here is the code snippet I am currently using to create a "Back" button: <INPUT type="button" value="Button" onclick="window.history.back(); return true;"> The issue I am facing is that on the previous page, there are two div elements. Initially, d ...

Enable the resizing of HTML images within a jeditorpane for user-friendly customization

Currently in the process of developing an application that enables users to insert images into a document. The document itself will be housed within a jEditorPane, allowing for HTML functionality to facilitate printing. I see no reason to switch components ...

The issue with `nth-of-type` not properly functioning within a list

I am having trouble altering the background of my divs when they are contained within an li element. It seems that the problem may be related to the arrangement of my elements. <ul class="featured-items"> <li><div class="inner">& ...