JavaScript Timer Countdown Minutes Seconds

JavaScript Timer Countdown Minutes Seconds
Code Snippet:Countdown-timer
Author: Luke Logan
Published: January 9, 2024
Last Updated: January 22, 2024
Downloads: 813
License: MIT
Edit Code online: View on CodePen
Read More

This JavaScript code snippet helps you to create a countdown timer with minutes and seconds that allows you to set countdowns for various durations. It works by calculating the time remaining in minutes and seconds, displaying it, and notifying when the timer ends. It helps you manage your time effectively, whether for short breaks or longer tasks.

It’s ideal for productivity apps, fitness routines, or cooking timers, providing a user-friendly countdown experience.

How to Create JavaScript Timer Countdown with Minutes and Seconds

1. First, create an HTML structure that includes buttons to set various countdown times and a display area for the timer. Customize it according to your design preferences.

  <div class="timer">
    <div class="timer__controls">
      <button data-time="20" class="timer__button">20 Secs</button>
      <button data-time="300" class="timer__button">Work 5</button>
      <button data-time="900" class="timer__button">Quick 15</button>
      <button data-time="1200" class="timer__button">Snack 20</button>
      <button data-time="3600" class="timer__button">Lunch Break</button>
      <form name="customForm" id="custom">
        <input type="text" name="minutes" placeholder="Enter Minutes">
      </form>
    </div>
    <div class="display">
      <h1 class="display__time-left"></h1>
      <p class="display__end-time"></p>
    </div>
  </div>

2. Apply CSS styles to your HTML elements, or you can use the following CSS code for a clean and attractive timer interface.

/*  
* CSS created by Wes Bos as part of his course. 
*/

main {
  box-sizing: border-box;
  font-size: 10px;
  background: #8E24AA;
  background: linear-gradient(45deg,  #42a5f5 0%,#478ed1 50%,#0d47a1 100%) !important;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body {
  margin: 0;
  text-align: center;
  font-family: 'Inconsolata', monospace;
}

.display__time-left {
  font-weight: 100;
  font-size: 20rem;
  margin: 0;
  color: white;
  text-shadow: 4px 4px 0 rgba(0,0,0,0.05);
}

.timer {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.timer__controls {
  display: flex;
}

.timer__controls > * {
  flex: 1;
}

.timer__controls form {
  flex: 1;
  display: flex;
}

.timer__controls input {
  flex: 1;
  border: 0;
  padding: 2rem;
}

.timer__button {
  background: none;
  border: 0;
  cursor: pointer;
  color: white;
  font-size: 2rem;
  text-transform: uppercase;
  background: rgba(0,0,0,0.1);
  border-bottom: 3px solid rgba(0,0,0,0.2);
  border-right: 1px solid rgba(0,0,0,0.2);
  padding: 1rem;
  font-family: 'Inconsolata', monospace;
}

.timer__button:hover,
.timer__button:focus {
  background: rgba(0,0,0,0.2);
  outline: 0;
}

.display {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.display__end-time {
  font-size: 4rem;
  color: white;
}

3. Finally, add the following JavaScript code to your project. This code creates the timer logic and handles user interactions. It consists of several functions to start, display, and end the countdown.

// Create the universal variable 'countdown' that lives in the window. 
let countdown;

const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');

// Get all data-keys with built-in timer settings
const buttons = document.querySelectorAll('[data-time');


// This is our main function
function timer(seconds) {
    //If any timers are already going, clear them
    clearInterval(countdown);

    // Date.now is a new JS function, will give time in MS.
    const now = Date.now();

    // Find time in SECONDS by multiplying default MS by 1000
    const then = now + seconds * 1000;

    // Run another function, defined below, as soon as this function is invoked
    displayTimeLeft(seconds);

    // Show the end time, another function defined below. 
    displayEndTime(then);

    // Set this function to the variable that lives in the browser. Set interval is a function that runs every 1000 ms 
    countdown = setInterval(() => {
        const secondsLeft = Math.round((then - Date.now()) / 1000);
      
        // Check when timer is done. 
        if(secondsLeft < 0){
            clearInterval(countdown);
            return;
        }
      
        //display it
        displayTimeLeft(secondsLeft);
      
      
// Run this function every 1000 ms
    }, 1000);
}


//Convert seconds to the formatted display value
function displayTimeLeft(seconds) {

    // Round seconds to whole numbers
    const minutes = Math.floor(seconds / 60);

    // Get the number of whole seconds remaining
    const remainderSeconds = seconds % 60;

    // Check if display needs a leading 0, if there is less than 10 seconds. so, '9' will display as '09'
    const display = `${minutes}:${remainderSeconds < 10 ? '0' : ''}${remainderSeconds}`;

    //Change title of document to be the seconds left
    document.title = display;
    timerDisplay.textContent = display;

}

// Show the static, unchanging END time
function displayEndTime(timestamp) {
  
    // Pass in the timestamp, which has all of the info below built in. This is a default JS method
    const end = new Date(timestamp);

    // Extract hours and minutes from the timestamp
    const hour = end.getHours();
    const minutes = end.getMinutes();

    // Display the time.
    // Check if past 12 noon, subtract 12 hours (not military time)
    // Check if less than 10 minutes. '9' becomes '09'
    endTime.textContent = `Be Back at ${hour > 12 ? hour - 12 : hour}:${minutes < 10 ? '0' : ''}${minutes}`;
}

// Get data from the data attribute buttons, and set them as the timer
function startTimer(){

    // ParseInt to only get whole number
    const seconds = parseInt(this.dataset.time);
    timer(seconds);
}

// Function to get data from pre-set button in data attributes
buttons.forEach(button => button.addEventListener('click', startTimer));

// If you give your form a custom name (name="minutes" in our HTML in this case), you can select it this way
document.customForm.addEventListener('submit', function(e){

    //prevent default browser behavior of reloading the page on time form submit
    e.preventDefault();

    //Get the number of minutes from the input field
    const mins = this.minutes.value;

    // Convert the minutes to seconds, which is what our timer uses
    timer(mins * 60);
    this.reset();

})


/*
todo/ ideas to enhance this timer: 
add timer sound when timer ends

add transitions to the countdown. 

add a "pause" button

*/

That’s all! hopefully, you have successfully created a Timer Countdown with Minutes and Seconds using JavaScript. Users can easily set timers for different purposes, making it a versatile addition to various projects. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X