DeveloperBreeze

In this tutorial, we will walk through how to create a countdown timer using JavaScript. The timer will dynamically display the remaining time (days, hours, minutes, and seconds) until a specified deadline, updating in real-time every second.

Prerequisites

To follow this tutorial, you need:

  • Basic knowledge of HTML, CSS, and JavaScript.
  • A text editor to write the code.
  • A browser to view the output.

Step-by-Step Breakdown

We will create a countdown timer that counts down to the 20th of the next month. If the current date is the 20th or later, it will count down to the 20th of the month after next. The countdown will stop once the deadline is reached.

1. Setting Up the HTML Structure

We'll need some HTML elements to display the countdown. Here's a simple structure:

<div id="clockdiv">
    <div>
        <span class="days"></span> Days
    </div>
    <div>
        <span class="hours"></span> Hours
    </div>
    <div>
        <span class="minutes"></span> Minutes
    </div>
    <div>
        <span class="seconds"></span> Seconds
    </div>
</div>

In this structure:

  • We have an element with the ID clockdiv that will contain the countdown timer.
  • Inside clockdiv, we have individual spans for displaying the number of days, hours, minutes, and seconds.

2. Writing the JavaScript Logic

Now, let's create the JavaScript code to calculate and display the remaining time.

Step 1: Create a Function to Calculate Remaining Time

We need a function that takes the end time (the deadline) as input and calculates the difference between the current time and the deadline:

function getTimeRemaining(endtime) {
    const total = Date.parse(endtime) - Date.now();
    const seconds = Math.floor((total / 1000) % 60);
    const minutes = Math.floor((total / 1000 / 60) % 60);
    const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
    const days = Math.floor(total / (1000 * 60 * 60 * 24));

    return {
        total,
        days,
        hours,
        minutes,
        seconds
    };
}
  • Date.parse(endtime) converts the end time into a timestamp (in milliseconds).
  • Date.now() gets the current time in milliseconds.
  • We calculate the difference (total), then use that to extract the days, hours, minutes, and seconds.
  • The function returns an object containing the remaining time.

Step 2: Create a Function to Update the Clock

Next, we need a function to update the timer every second:

function initializeClock(id, endtime) {
    const clock = document.getElementById(id);
    const daysSpan = clock.querySelector('.days');
    const hoursSpan = clock.querySelector('.hours');
    const minutesSpan = clock.querySelector('.minutes');
    const secondsSpan = clock.querySelector('.seconds');

    function updateClock() {
        const t = getTimeRemaining(endtime);

        daysSpan.innerHTML = t.days;
        hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
        minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
        secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

        if (t.total <= 0) {
            clearInterval(timeinterval);
        }
    }

    updateClock();
    const timeinterval = setInterval(updateClock, 1000);
}
  • initializeClock() takes two parameters: id (the ID of the HTML element where the timer will be displayed) and endtime (the deadline).
  • updateClock() retrieves the remaining time using the getTimeRemaining() function and updates the corresponding spans (days, hours, minutes, seconds).
  • setInterval() ensures that the updateClock() function runs every second (1000 milliseconds).
  • If the total remaining time becomes zero or negative, the interval is cleared, stopping the countdown.

Step 3: Set the Deadline

Now, let’s determine the deadline. If the current day of the month is on or after the 20th, we will set the countdown to the 20th of the next month. Otherwise, it will count down to the 20th of the current month:

let date = new Date();
let count;
if (date.getDate() >= 20) {
    count = date.getMonth() + 2; // Move to the next month
} else {
    count = date.getMonth() + 1; // Use the current month
}

let year = date.getFullYear(); // Get the current year
let date_str = `${year}-${count.toString().padStart(2, '0')}-20T23:59:59`; // Format the deadline as YYYY-MM-20
let deadline = new Date(date_str);
  • We check if the current day is greater than or equal to the 20th. If true, the deadline is set to the 20th of the next month; otherwise, it’s set to the 20th of the current month.
  • The deadline is formatted as YYYY-MM-20T23:59:59, ensuring the countdown ends at midnight on the 20th.

Step 4: Initialize the Clock

Finally, we need to initialize the clock by calling initializeClock() with the clockdiv ID and the calculated deadline:

initializeClock('clockdiv', deadline);

3. Full Code Example

Here’s the complete code for the countdown timer:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Countdown Timer</title>
    <style>
        #clockdiv {
            font-family: sans-serif;
            color: #333;
            display: flex;
            justify-content: center;
            gap: 20px;
        }
        #clockdiv div {
            font-size: 30px;
        }
    </style>
</head>
<body>

<div id="clockdiv">
    <div><span class="days"></span> Days</div>
    <div><span class="hours"></span> Hours</div>
    <div><span class="minutes"></span> Minutes</div>
    <div><span class="seconds"></span> Seconds</div>
</div>

<script>
    function getTimeRemaining(endtime) {
        const total = Date.parse(endtime) - Date.now();
        const seconds = Math.floor((total / 1000) % 60);
        const minutes = Math.floor((total / 1000 / 60) % 60);
        const hours = Math.floor((total / (1000 * 60 * 60)) % 24);
        const days = Math.floor(total / (1000 * 60 * 60 * 24));

        return { total, days, hours, minutes, seconds };
    }

    function initializeClock(id, endtime) {
        const clock = document.getElementById(id);
        const daysSpan = clock.querySelector('.days');
        const hoursSpan = clock.querySelector('.hours');
        const minutesSpan = clock.querySelector('.minutes');
        const secondsSpan = clock.querySelector('.seconds');

        function updateClock() {
            const t = getTimeRemaining(endtime);

            daysSpan.innerHTML = t.days;
            hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
            minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
            secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

            if (t.total <= 0) {
                clearInterval(timeinterval);
            }
        }

        updateClock();
        const timeinterval = setInterval(updateClock, 1000);
    }

    let date = new Date();
    let count;
    if (date.getDate() >= 20) {
        count = date.getMonth() + 2;
    } else {
        count = date.getMonth() + 1;
    }
    let year = date.getFullYear();
    let date_str = `${year}-${count.toString().padStart(2, '0')}-20T23:59:59`;
    let deadline = new Date(date_str);

    initializeClock('clockdiv', deadline);
</script>

</body>
</html>

4. Conclusion

This tutorial has demonstrated how to create a countdown timer using JavaScript. By calculating the remaining time until a specified deadline, we can continuously update the display with days, hours, minutes, and seconds. This approach is adaptable for various use cases, such as event countdowns, sale timers, or promotional offers.

Key Takeaways:

  • We used JavaScript’s Date object to work with time.
  • The setInterval() function enabled real-time updates.
  • We formatted the remaining time into days, hours, minutes, and seconds for a user-friendly display.

With this setup, you can modify the deadline logic or style the clock to fit your specific requirements!

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

How to Translate URLs in React (2025 Guide)

Install necessary dependencies:

npm install react-router-dom i18next react-i18next i18next-browser-languagedetector

May 04, 2025
Read More
Tutorial

Globalization in React (2025 Trends & Best Practices)

Red = luck in China, danger in the West.

  • Adapt units and metrics

May 04, 2025
Read More
Tutorial

Implementing Internationalization (i18n) in a Large React Application (2025 Guide)

If you don’t have a project yet, initialize a new one:

npx create-react-app react-i18n-demo
cd react-i18n-demo

May 04, 2025
Read More
Tutorial

Building Micro-Frontends with Webpack Module Federation (2025 Guide)

Use shared in Module Federation to prevent loading duplicate libraries (like react, vue, etc.).

Use a design system or tokens for consistent UI/UX across micro-apps.

May 04, 2025
Read More
Tutorial

State Management Beyond Redux: Using Zustand for Scalable React Apps

These features make Zustand an attractive choice for developers looking to manage state in a more concise and efficient manner.

Getting started with Zustand is straightforward. Here's how you can integrate it into your React application:

May 03, 2025
Read More
Tutorial

Mastering React Rendering Performance with Memoization and Context

For components that perform heavy computations, useMemo can cache the result of a calculation, recomputing it only when its dependencies change.([Content That Scales][5])

import React, { useState, useMemo } from 'react';

function ExpensiveComponent({ data }) {
  const processedData = useMemo(() => {
    // Expensive computation
    return data.map(item => /* processing */ item);
  }, [data]);

  return <div>{/* render processedData */}</div>;
}

May 03, 2025
Read More
Tutorial
javascript

Comparison and Logical Operators

// AND operator
console.log(true && true); // true
console.log(true && false); // false

// OR operator
console.log(false || true); // true
console.log(false || false); // false

// NOT operator
console.log(!true); // false
console.log(!false); // true

Use comparison and logical operators together for complex conditions.

Dec 11, 2024
Read More
Tutorial
javascript

Arithmetic Operators

  • Increases a variable by one.
  • Postfix Increment (i++):
     let i = 5;
     console.log(i++); // Outputs 5, then i becomes 6
     console.log(i);   // Outputs 6

Dec 11, 2024
Read More
Tutorial
javascript

Non-Primitive Data Types (Objects, Arrays, and Functions)

Example:

let car = { make: "Toyota", model: "Corolla", year: 2020 };
car.color = "blue";
console.log(car);

let colors = ["red", "green", "blue"];
colors.push("yellow");
colors.shift();
console.log(colors);

const sum = (a, b) => a + b;
console.log(sum(10, 15)); // 25

Dec 11, 2024
Read More
Tutorial
javascript

Primitive Data Types

    console.log(10 / 0); // Infinity
  • NaN: Result of an invalid number operation.

Dec 11, 2024
Read More
Tutorial
javascript

Variables and Constants

     {
       let x = 10;
       console.log(x); // 10
     }
     console.log(x); // Error: x is not defined
  • Variables are accessible within the entire function they are declared in.
  • Example:

Dec 10, 2024
Read More
Tutorial
javascript

Hello World and Comments

  • In a browser:
  • Open the console (Ctrl+Shift+J or Cmd+Option+J) and type the code.
  • In Node.js:
  • Save the code in a file (e.g., hello.js) and run it using:
       node hello.js

Dec 10, 2024
Read More
Tutorial
javascript

Using Node.js to Run JavaScript

  • Install a package:
     npm install lodash

Dec 10, 2024
Read More
Tutorial
javascript

Running JavaScript in the Browser Console

  • Right-click on the webpage and select Inspect or press Ctrl+Shift+I.
  • Open the Console tab.
  • Go to Safari > Preferences > Advanced and enable the Show Develop menu in menu bar option.
  • Right-click on the webpage and select Inspect Element or press Cmd+Option+C.
  • Click on the Console tab.

Dec 10, 2024
Read More
Tutorial
javascript

Installing a Code Editor (e.g., VS Code)

  • Open the Extensions view (Ctrl+Shift+X or Cmd+Shift+X on macOS).
  • Recommended extensions for JavaScript:
  • ESLint: Linting and error-checking.
  • Prettier: Code formatting.
  • JavaScript (ES6) Code Snippets: Useful code snippets.
  • Live Server: Preview your code in the browser.
  • Customize the editor's look by choosing a theme:
  • Navigate to File > Preferences > Color Theme.
  • Popular themes: Dark+, Dracula, Monokai.

Dec 10, 2024
Read More
Tutorial
javascript

JavaScript in Modern Web Development

  • Frameworks like Electron allow creating cross-platform desktop apps.
  • Example: Visual Studio Code.
  • JavaScript is used in IoT devices for controlling hardware and sensors.
  • Example: Node.js-based IoT applications.

Dec 10, 2024
Read More
Tutorial
javascript

History and Evolution

  • ES6 (2015): A landmark update introduced features like let, const, arrow functions, classes, template literals, and more.
  • Frequent updates: JavaScript now sees yearly updates, introducing features like async/await, optional chaining, and modules.
  • JavaScript powers not only browsers but also servers (Node.js), mobile apps, and even IoT devices.
  • Widely used frameworks like React, Angular, and Vue have further cemented its role in modern development.

Dec 10, 2024
Read More
Tutorial
javascript css +1

How to Create a Chrome Extension for Automating Tweets on X (Twitter)

The background.js file contains the logic for automating tweets. Copy the following code into background.js:

let intervalId = null;
const tweets = ["https://developerbreeze.com/post/59"];
let engage = [
  "Want to code like a pro? 🚀 These tutorials will get you there in no time! 💻🔥",
  "Struggling with coding? 🧠 These beginner-friendly tips will blow your mind! 🤯",
];

let currentTweetIndex = 0;

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "start") {
    if (!intervalId) {
      intervalId = setInterval(() => {
        const currentTweet = tweets[currentTweetIndex];
        const randomEngage = engage[Math.floor(Math.random() * engage.length)];
        const tweet = `${randomEngage} ${currentTweet}`;

        const encodedTweet = encodeURIComponent(tweet);
        const shareUrl = `https://x.com/intent/tweet?text=${encodedTweet}`;

        chrome.tabs.create({ url: shareUrl, active: true }, (tab) => {
          chrome.tabs.onUpdated.addListener(function listener(tabId, info) {
            if (tabId === tab.id && info.status === "complete") {
              chrome.tabs.onUpdated.removeListener(listener);
              chrome.scripting.executeScript({
                target: { tabId },
                files: ["content.js"],
              });
            }
          });
        });

        currentTweetIndex = (currentTweetIndex + 1) % tweets.length;
      }, 300000); // Post every 5 minutes
      sendResponse({ status: "Running" });
    } else {
      sendResponse({ status: "Already Running" });
    }
  } else if (request.action === "stop") {
    clearInterval(intervalId);
    intervalId = null;
    sendResponse({ status: "Stopped" });
  }
});

Dec 10, 2024
Read More
Tutorial
javascript

Advanced State Management in React Using Redux Toolkit

Dynamic reducer loading is an advanced pattern used in large-scale applications. It allows you to add reducers on the fly, optimizing the app's performance and avoiding loading unnecessary reducers upfront.

In src/app/store.js, enhance the store to support dynamic reducer injection:

Dec 09, 2024
Read More
Tutorial
php

Building a Laravel Application with Vue.js for Dynamic Interfaces

   module.exports = {
       content: [
           './resources/**/*.blade.php',
           './resources/**/*.js',
           './resources/**/*.vue',
       ],
       theme: {
           extend: {},
       },
       plugins: [],
   };

Open or create resources/css/app.css and add the Tailwind CSS directives:

Nov 16, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!