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)

Create i18n.js:

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';

import en from './locales/en.json';
import fr from './locales/fr.json';

i18n
  .use(LanguageDetector)
  .use(initReactI18next)
  .init({
    resources: { en: { translation: en }, fr: { translation: fr } },
    fallbackLng: 'en',
    interpolation: {
      escapeValue: false,
    },
  });

export default i18n;

May 04, 2025
Read More
Tutorial

Globalization in React (2025 Trends & Best Practices)

Switch dir dynamically:

document.documentElement.setAttribute('dir', i18n.language === 'ar' ? 'rtl' : 'ltr');

May 04, 2025
Read More
Tutorial

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

Example fr.json:

{
  "welcome": "Bienvenue sur notre plateforme !",
  "language": "Langue",
  "date_example": "La date d'aujourd'hui est {{date, datetime}}",
  "price_example": "Prix : {{price, currency}}"
}

May 04, 2025
Read More
Tutorial

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

  • Increased complexity
  • More testing needed (integration)
  • SEO handling is trickier in client-rendered apps

To improve Google indexing:

May 04, 2025
Read More
Tutorial

State Management Beyond Redux: Using Zustand for Scalable React Apps

  • Project Size: For small to medium-sized projects, Zustand's simplicity can accelerate development.
  • Team Experience: Teams new to state management may find Zustand's learning curve more approachable.
  • Boilerplate Reduction: If minimizing boilerplate is a priority, Zustand offers a cleaner setup.
  • Performance Needs: Zustand's selective rendering can enhance performance in applications with frequent state updates.

However, for large-scale applications requiring complex state interactions, middleware, and extensive tooling, Redux might still be the preferred choice.

May 03, 2025
Read More
Tutorial

Mastering React Rendering Performance with Memoization and Context

Example:

import React from 'react';

const Greeting = React.memo(function Greeting({ name }) {
  console.log("Greeting rendered");
  return <h3>Hello{name && ', '}{name}!</h3>;
});

May 03, 2025
Read More
Tutorial
javascript

Comparison and Logical Operators

Use comparison and logical operators together for complex conditions.

Example:

Dec 11, 2024
Read More
Tutorial
javascript

Arithmetic Operators

     let a = 12;
     let b = 4;
     console.log("Addition:", a + b);        // 16
     console.log("Subtraction:", a - b);     // 8
     console.log("Multiplication:", a * b);  // 48
     console.log("Division:", a / b);        // 3
     console.log("Modulus:", a % b);         // 0
  • Initialize counter to 10.
  • Use both prefix and postfix increment/decrement operators and observe the outputs.

Dec 11, 2024
Read More
Tutorial
javascript

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

  • Bracket notation:
    console.log(person["age"]); // 25

Dec 11, 2024
Read More
Tutorial
javascript

Primitive Data Types

  let currentUser = null;
  console.log(currentUser); // null

Symbols are unique identifiers.

Dec 11, 2024
Read More
Tutorial
javascript

Variables and Constants

  • Valid: name, _age, $price
  • Invalid: 1name, @value
  • age and Age are different.

Dec 10, 2024
Read More
Tutorial
javascript

Hello World and Comments

  • In your script file or console, type:
     console.log("Hello, World!");

Dec 10, 2024
Read More
Tutorial
javascript

Using Node.js to Run JavaScript

     node example.js
  • Output:

Dec 10, 2024
Read More
Tutorial
javascript

Running JavaScript in the Browser Console

Modern browsers come with built-in developer tools that include a JavaScript console, a powerful environment for writing, testing, and debugging JavaScript code. In this tutorial, we’ll learn how to access and use the console.

  • Quick Testing: Test snippets of JavaScript code without setting up a development environment.
  • Debugging: Check errors and log values during code execution.
  • Real-Time Interaction: Manipulate and inspect web page elements dynamically.

Dec 10, 2024
Read More
Tutorial
javascript

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

  • Go to File > Preferences > Settings and search for "Auto Save."
  • Set it to afterDelay for smoother development.
  • Open VS Code and create a file with the .js extension (e.g., test.js).

Dec 10, 2024
Read More
Tutorial
javascript

JavaScript in Modern Web Development

JavaScript isn't limited to the browser anymore. It's being used in diverse domains:

  • Tools like React Native enable building native apps using JavaScript.
  • Example: Facebook's mobile app.

Dec 10, 2024
Read More
Tutorial
javascript

History and Evolution

  • JavaScript was standardized under the name ECMAScript by ECMA International.
  • The first edition of ECMAScript (ES1) laid the foundation for modern JavaScript.
  • Competing browsers (Netscape, Internet Explorer) implemented JavaScript differently, leading to compatibility issues.
  • The advent of libraries like jQuery (2006) helped developers write cross-browser code more easily.

Dec 10, 2024
Read More
Tutorial
javascript css +1

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

Create a new folder for your project, and within it, create the following files:

- manifest.json
- background.js
- content.js
- popup.html
- popup.js

Dec 10, 2024
Read More
Tutorial
javascript

Advanced State Management in React Using Redux Toolkit

  • How configureStore works and why it's better than traditional Redux.
  • Adding middleware for additional functionality.
  • Connecting components with useSelector and useDispatch.
  • Passing data between Redux and UI components.

Dec 09, 2024
Read More
Tutorial
php

Building a Laravel Application with Vue.js for Dynamic Interfaces

Add the following configuration:

   import { defineConfig } from 'vite';
   import laravel from 'laravel-vite-plugin';
   import vue from '@vitejs/plugin-vue';

   export default defineConfig({
       plugins: [
           laravel({
               input: ['resources/css/app.css', 'resources/js/app.js'],
               refresh: true,
           }),
           vue(),
       ],
       resolve: {
           alias: {
               vue: 'vue/dist/vue.esm-bundler.js', // Ensures runtime template compilation works
           },
       },
   });

Nov 16, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!