DEV Community

Cover image for Day-8 of Learning JavaScript: Ticking Time Bomb: A Playful Guide to Crafting Your Own Countdown Timer
Aniket Saini
Aniket Saini

Posted on

Day-8 of Learning JavaScript: Ticking Time Bomb: A Playful Guide to Crafting Your Own Countdown Timer

Ever wished you had a stopwatch for the end of a bad date? Or a personal soundtrack to the last bite of pizza?

Welcome to the world of countdown timers, where anticipation becomes your best friend (and procrastination, your worst enemy). No more endless staring at clocks or nervously tapping your foot. With a little JavaScript magic, you can turn any deadline into a dramatic countdown, complete with flashing lights and maybe even a disco ball (okay, maybe just the lights).

This article is your passport to the thrilling land of time travel (sort of). We’ll be whipping up timers that count down from birthday parties to laundry loads, all with the grace and power of a seasoned code whisperer. So grab your laptop, dust off your caffeine supply, and get ready to conquer the tyranny of “how much longer?!”

Think of this as your chance to become the puppet master of time, twisting and turning its gears to your whim. You’ll be the envy of your friends, the hero of your kitchen, and the undisputed champion of waiting-in-line sanity.

So strap in, buttercup. We’re about to dive into the dazzling world of dynamic countdown timers, where every second is a mini-adventure! (Disclaimer: actual adventure levels may vary, but the fun factor is guaranteed.)

Now, without further ado, let’s unleash the kraken of code and make time tremble before our JavaScript might!

What is a countdown timer?

A countdown timer is a device or a program that displays the remaining time until a certain event or deadline. For example, you might have seen countdown timers on websites that show how much time is left until a sale ends, or on apps that help you track your productivity or fitness goals.

A countdown timer can be useful for various purposes, such as:

  • Creating a sense of urgency or excitement for your visitors or customers

  • Motivating yourself or others to complete a task or a challenge within a given time limit

  • Reminding yourself or others of an important date or occasion

  • Having fun with games or quizzes that require quick thinking or reaction

Why do we need a countdown timer?

A countdown timer can help us achieve our objectives and improve our performance in different aspects of life. Some of the benefits of using a countdown timer are:

  • It can help us manage our time better and avoid procrastination

  • It can help us focus on the most important or urgent tasks and prioritize them accordingly

  • It can help us break down large or complex tasks into smaller or simpler ones and track our progress

  • It can help us set realistic and achievable goals and measure our results

  • It can help us increase our productivity and efficiency and reduce stress and anxiety

    How are we going to create a countdown timer?

To create a countdown timer, we need to use some basic HTML, CSS, and JavaScript code.

In this article, we will focus on the JavaScript code that will make our countdown timer work. We will use some common JavaScript concepts, such as:

  • Variables

  • Functions

  • Events

  • Methods

Let’s see how we can use these concepts to create a simple countdown timer that counts down from 10 minutes to zero. We will also add some basic HTML and CSS code to create a simple user interface for our timer.


Chapter 1 : HTML Code

The HTML code defines the structure and content of our web page. We will use some HTML elements, such as:

  • <div>: This is a container element that can hold other elements or content. We will use <div> elements to create the main container, the timer display, and the buttons for our countdown timer.

  • <span>: This is an inline element that can hold text or other inline elements. We will use <span> elements to display the minutes and seconds of our countdown timer.

  • <button>: This is an element that can create a clickable button. We will use <button> elements to create the start and reset buttons for our countdown timer.

Here is the HTML code for our countdown timer:

<!-- This is the main container for our countdown timer -->
<div id="timer-container">
  <!-- This is the timer display that shows the remaining time -->
  <div id="timer-display">
    <!-- This is the span element that shows the minutes -->
    <span id="minutes">10</span>
    <!-- This is the span element that shows the colon separator -->
    <span>:</span>
    <!-- This is the span element that shows the seconds -->
    <span id="seconds">00</span>
  </div>

  <div class="btn">
    <!-- This is the button that starts the countdown timer -->
    <button id="start-button">Start</button>
    <!-- This is the button that resets the countdown timer -->
    <button id="reset-button">Reset</button>
  </div>
</div>
Enter fullscreen mode Exit fullscreen mode

Chapter 2 : CSS Code

The CSS code defines the style and format of our web page. We will use some CSS properties, such as:

  • width and height: These properties specify the width and height of an element. We will use these properties to set the size of our main container and our buttons.

  • margin and padding: These properties specify the space around and inside an element. We will use these properties to create some space between our elements and make them look nicer.

  • font-family and font-size: These properties specify the font family and font size of the text. We will use these properties to change the appearance of our timer display and our buttons.

  • text-align and vertical-align: These properties specify the horizontal and vertical alignment of the text. We will use these properties to center our timer display and our buttons.

  • border and border-radius: These properties specify the border and the border radius of an element. We will use these properties to create a border around our main container and make our buttons look rounder.

  • background-color and color: These properties specify the background color and the text color of an element. We will use these properties to change the color of our main container, our timer display, and our buttons.

Here is the CSS code for our countdown timer:

html,
body {
  height: 100%;
  margin: 0;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

#timer-container {
  width: 300px;
  height: 200px;
  margin: auto;
  border-style: none;
  border-radius: 10px;
  background-color: lightgray;
}

/* This is the style for our timer display */
#timer-display {
  width: 100%;
  height: 50%;
  font-family: Roboto, System-ui;
  font-size: 58px;
  font-weight: bold;
  text-align: center;
  padding-top: 20px;
  color: black;
}

.btn {
  display: flex;
  align-item: center;
  justify-content: space-around;
}

/* This is the style for our buttons */
button {
  width: 100px;
  height: 50px;
  font-family: Roboto, System-ui;
  font-size: 24px;
  font-weight: 600;
  text-align: center;
  border-radius: 10px;
  color: black;
  background-color: lightgray;
}

button:hover {
  cursor: pointer;
}

#start-button {
  border: 2px solid #33FF57;
}

#start-button:hover {
  background-color: #33FF57;
}

#reset-button {
  border: 2px solid Tomato;
}

#reset-button:hover {
  background-color: Tomato;
}
Enter fullscreen mode Exit fullscreen mode

Chapter 3 : JavaScript code

The JavaScript code defines the functionality and interactivity of our web page. We will use some JavaScript variables, functions, events, and methods, such as:

  • document.getElementById()

  • addEventListener()

  • setInterval()

  • clearInterval()

  • parseInt()

  • Math.Floor()

  • String.padStart()

Here is the JavaScript code for our countdown timer:

// This is the variable that stores the start time in seconds
// We set it to 10 minutes, which is 600 seconds
let startTime = 600;

// This is the variable that stores the end time in seconds
// We set it to zero, which is when the countdown ends
let endTime = 0;

// This is the variable that stores the remaining time in seconds
// We set it to the start time initially
let remainingTime = startTime;

// This is the variable that stores the timer that runs every second
// We set it to null initially
let timer = null;

// This is the function that calculates the remaining time
function calculateRemainingTime() {
  // We subtract one second from the remaining time
  remainingTime = remainingTime - 1;
  // We return the remaining time
  return remainingTime;
}

// This is the function that updates the display with the remaining time
function updateDisplay() {
  // We get the minutes and seconds from the remaining time
  // We use Math.floor to round down the numbers
  // We use String.padStart to add a leading zero if the numbers are less than 10
  let minutes = Math.floor(remainingTime / 60).toString().padStart(2, "0");
  let seconds = Math.floor(remainingTime % 60).toString().padStart(2, "0");

  // We get the elements that display the minutes and seconds
  // We use document.getElementById to access them by their id
  let minutesElement = document.getElementById("minutes");
  let secondsElement = document.getElementById("seconds");

  // We update the text content of the elements with the minutes and seconds
  minutesElement.textContent = minutes;
  secondsElement.textContent = seconds;
}

// This is the function that checks if the countdown is over
function checkCountdown() {
  // We check if the remaining time is equal to the end time
  if (remainingTime === endTime) {
    // We stop the timer that runs every second
    // We use clearInterval to stop it
    clearInterval(timer);

    // We get the element that displays the timer
    // We use document.getElementById to access it by its id
    let timerDisplay = document.getElementById("timer-display");

    // We update the text content of the element with a message that says "Time's up!"
    timerDisplay.textContent = "Time's up!";
  }
}

// This is the function that starts the countdown timer
function startTimer() {
  // We check if the timer is null, which means it is not running
  if (timer === null) {
    // We create a timer that runs a function every second
    // We use setInterval to create it
    // We store the timer in the timer variable
    timer = setInterval(function () {
      // We call the function that calculates the remaining time
      calculateRemainingTime();
      // We call the function that updates the display
      updateDisplay();
      // We call the function that checks if the countdown is over
      checkCountdown();
    }, 1000); // 1000 milliseconds is equal to 1 second
  }
}

// This is the function that resets the countdown timer
function resetTimer() {
  // We stop the timer that runs every second
  // We use clearInterval to stop it
  clearInterval(timer);

  // We reset the timer variable to null
  timer = null;

  // We reset the remaining time variable to the start time
  remainingTime = startTime;

  // We call the function that updates the display
  updateDisplay();
}

// We get the elements that are the buttons
// We use document.getElementById to access them by their id
let startButton = document.getElementById("start-button");
let resetButton = document.getElementById("reset-button");

// We add click event listeners to the buttons
// We use addEventListener to add them
// We pass the name of the event and the name of the function that runs when the event occurs
startButton.addEventListener("click", startTimer);
resetButton.addEventListener("click", resetTimer);
Enter fullscreen mode Exit fullscreen mode

What JavaScript concepts did we use?

In this article, we used some common JavaScript concepts to create a simple countdown timer, such as:

  • Variables: These are containers that store data or values that we can use in our code. We used variables to store the start time, the end time, the remaining time, and the timer of our countdown timer.

  • Functions: These are blocks of code that perform a specific task or action. We used functions to calculate the remaining time, update the display, check the countdown, start the timer, and reset the timer.

  • Events: These are actions or occurrences that happen on a web page, such as clicking a button, loading a page, or resizing a window. We used events to start or reset our countdown timer when the user clicked the buttons.

  • document.getElementById: This is a built-in JavaScript method that allows us to access an element by its id attribute. We will use this method to get the elements that we need for our countdown timer, such as the timer display, the minutes, the seconds, and the buttons.

  • addEventListener: This is a built-in JavaScript method that allows us to attach an event listener to an element. An event listener is a function that runs when a certain event occurs on the element. We will use this method to add click event listeners to our buttons, so that we can start or reset our countdown timer when the user clicks them.

  • setInterval and clearInterval: These are built-in JavaScript methods that allow us to execute a function repeatedly at a specified interval or stop it from executing. We used setInterval to update our display every second, and clearInterval to stop the timer when it reached zero.

  • parseInt: This is a built-in JavaScript method that allows us to convert a string into an integer. We used parseInt to get the numerical values of the minutes and seconds from the text content of the elements.

  • Math.floor: This is a built-in JavaScript method that allows us to round down a number to the nearest integer. We used Math.floor to get the whole number of minutes and seconds from the remaining time.

  • String.padStart: This is a built-in JavaScript method that allows us to pad a string with another string until it reaches a certain length. We used String.padStart to add a leading zero to the minutes and seconds if they were less than 10.

The Grand Finale: Your Time Machine is Ready

Open your HTML file in a web browser and click the “Start Countdown” button. Behold the magic as the timer counts down from 5 minutes! You’ve just crafted your own Countdown Timer, turning the abstract concept of time into a playful, interactive experience.

CLICK HERE to check Final Output.



Countdown Timer Final Output

Epilogue: Time Marches On

Congratulations, time traveler! You’ve successfully navigated the realms of web development, creating a Countdown Timer that can add excitement to any digital landscape. As you continue your coding journey, remember to experiment, explore, and embrace the wonder of building things with code. May your future be filled with countless moments of enchantment! Happy coding! 😊

Top comments (0)