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: 1,140
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.

  1. <div class="timer">
  2. <div class="timer__controls">
  3. <button data-time="20" class="timer__button">20 Secs</button>
  4. <button data-time="300" class="timer__button">Work 5</button>
  5. <button data-time="900" class="timer__button">Quick 15</button>
  6. <button data-time="1200" class="timer__button">Snack 20</button>
  7. <button data-time="3600" class="timer__button">Lunch Break</button>
  8. <form name="customForm" id="custom">
  9. <input type="text" name="minutes" placeholder="Enter Minutes">
  10. </form>
  11. </div>
  12. <div class="display">
  13. <h1 class="display__time-left"></h1>
  14. <p class="display__end-time"></p>
  15. </div>
  16. </div>

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

  1. /*
  2. * CSS created by Wes Bos as part of his course.
  3. */
  4.  
  5. main {
  6. box-sizing: border-box;
  7. font-size: 10px;
  8. background: #8E24AA;
  9. background: linear-gradient(45deg, #42a5f5 0%,#478ed1 50%,#0d47a1 100%) !important;
  10. }
  11.  
  12. *, *:before, *:after {
  13. box-sizing: inherit;
  14. }
  15.  
  16. body {
  17. margin: 0;
  18. text-align: center;
  19. font-family: 'Inconsolata', monospace;
  20. }
  21.  
  22. .display__time-left {
  23. font-weight: 100;
  24. font-size: 20rem;
  25. margin: 0;
  26. color: white;
  27. text-shadow: 4px 4px 0 rgba(0,0,0,0.05);
  28. }
  29.  
  30. .timer {
  31. display: flex;
  32. min-height: 100vh;
  33. flex-direction: column;
  34. }
  35.  
  36. .timer__controls {
  37. display: flex;
  38. }
  39.  
  40. .timer__controls > * {
  41. flex: 1;
  42. }
  43.  
  44. .timer__controls form {
  45. flex: 1;
  46. display: flex;
  47. }
  48.  
  49. .timer__controls input {
  50. flex: 1;
  51. border: 0;
  52. padding: 2rem;
  53. }
  54.  
  55. .timer__button {
  56. background: none;
  57. border: 0;
  58. cursor: pointer;
  59. color: white;
  60. font-size: 2rem;
  61. text-transform: uppercase;
  62. background: rgba(0,0,0,0.1);
  63. border-bottom: 3px solid rgba(0,0,0,0.2);
  64. border-right: 1px solid rgba(0,0,0,0.2);
  65. padding: 1rem;
  66. font-family: 'Inconsolata', monospace;
  67. }
  68.  
  69. .timer__button:hover,
  70. .timer__button:focus {
  71. background: rgba(0,0,0,0.2);
  72. outline: 0;
  73. }
  74.  
  75. .display {
  76. flex: 1;
  77. display: flex;
  78. flex-direction: column;
  79. align-items: center;
  80. justify-content: center;
  81. }
  82.  
  83. .display__end-time {
  84. font-size: 4rem;
  85. color: white;
  86. }

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.

  1. // Create the universal variable 'countdown' that lives in the window.
  2. let countdown;
  3.  
  4. const timerDisplay = document.querySelector('.display__time-left');
  5. const endTime = document.querySelector('.display__end-time');
  6.  
  7. // Get all data-keys with built-in timer settings
  8. const buttons = document.querySelectorAll('[data-time');
  9.  
  10.  
  11. // This is our main function
  12. function timer(seconds) {
  13. //If any timers are already going, clear them
  14. clearInterval(countdown);
  15.  
  16. // Date.now is a new JS function, will give time in MS.
  17. const now = Date.now();
  18.  
  19. // Find time in SECONDS by multiplying default MS by 1000
  20. const then = now + seconds * 1000;
  21.  
  22. // Run another function, defined below, as soon as this function is invoked
  23. displayTimeLeft(seconds);
  24.  
  25. // Show the end time, another function defined below.
  26. displayEndTime(then);
  27.  
  28. // Set this function to the variable that lives in the browser. Set interval is a function that runs every 1000 ms
  29. countdown = setInterval(() => {
  30. const secondsLeft = Math.round((then - Date.now()) / 1000);
  31. // Check when timer is done.
  32. if(secondsLeft < 0){
  33. clearInterval(countdown);
  34. return;
  35. }
  36. //display it
  37. displayTimeLeft(secondsLeft);
  38. // Run this function every 1000 ms
  39. }, 1000);
  40. }
  41.  
  42.  
  43. //Convert seconds to the formatted display value
  44. function displayTimeLeft(seconds) {
  45.  
  46. // Round seconds to whole numbers
  47. const minutes = Math.floor(seconds / 60);
  48.  
  49. // Get the number of whole seconds remaining
  50. const remainderSeconds = seconds % 60;
  51.  
  52. // Check if display needs a leading 0, if there is less than 10 seconds. so, '9' will display as '09'
  53. const display = `${minutes}:${remainderSeconds < 10 ? '0' : ''}${remainderSeconds}`;
  54.  
  55. //Change title of document to be the seconds left
  56. document.title = display;
  57. timerDisplay.textContent = display;
  58.  
  59. }
  60.  
  61. // Show the static, unchanging END time
  62. function displayEndTime(timestamp) {
  63. // Pass in the timestamp, which has all of the info below built in. This is a default JS method
  64. const end = new Date(timestamp);
  65.  
  66. // Extract hours and minutes from the timestamp
  67. const hour = end.getHours();
  68. const minutes = end.getMinutes();
  69.  
  70. // Display the time.
  71. // Check if past 12 noon, subtract 12 hours (not military time)
  72. // Check if less than 10 minutes. '9' becomes '09'
  73. endTime.textContent = `Be Back at ${hour > 12 ? hour - 12 : hour}:${minutes < 10 ? '0' : ''}${minutes}`;
  74. }
  75.  
  76. // Get data from the data attribute buttons, and set them as the timer
  77. function startTimer(){
  78.  
  79. // ParseInt to only get whole number
  80. const seconds = parseInt(this.dataset.time);
  81. timer(seconds);
  82. }
  83.  
  84. // Function to get data from pre-set button in data attributes
  85. buttons.forEach(button => button.addEventListener('click', startTimer));
  86.  
  87. // If you give your form a custom name (name="minutes" in our HTML in this case), you can select it this way
  88. document.customForm.addEventListener('submit', function(e){
  89.  
  90. //prevent default browser behavior of reloading the page on time form submit
  91. e.preventDefault();
  92.  
  93. //Get the number of minutes from the input field
  94. const mins = this.minutes.value;
  95.  
  96. // Convert the minutes to seconds, which is what our timer uses
  97. timer(mins * 60);
  98. this.reset();
  99.  
  100. })
  101.  
  102.  
  103. /*
  104. todo/ ideas to enhance this timer:
  105. add timer sound when timer ends
  106.  
  107. add transitions to the countdown.
  108.  
  109. add a "pause" button
  110.  
  111. */

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