How to Build a Timer with Sound effect Using JavaScript

In this tutorial, we will learn how to build a timer with a sound effect using JavaScript.
By the end of this tutorial, you will have a timer with a sound effect that you can use in various scenarios.
Let’s get started!


Build a Timer with Sound effect Using JavaScript

Now let’s start with code and detailed explanation. The code below is your JavaScript file code.

document.addEventListener('DOMContentLoaded', () => {
     // logic for timer and sound...
});
  • Firstly, we must start with the ‘DOMContentLoaded’ event-listener, because this ensures that the JavaScript code runs only after loading the entire HTML document.
  • Furthermore, the rest of the code will be inside this event listener.
Variable Declarations:
const timerDisplay = document.getElementById('timer');
const startBtn = document.getElementById('startBtn');
const resetBtn = document.getElementById('resetBtn');
const Sound = document.getElementById('Sound');
const durationInput = document.getElementById('duration');
const setDurationBtn = document.getElementById('setDurationBtn');
  • Let’s start with some constant variable declarations for use in our code.
  • Additionally, these constants store references to the HTML elements for the timer display, start button, reset button, sound element, duration input field, and button to set the duration, respectively.
let timer;
let seconds = parseInt(durationInput.value, 10);
  • we have to define ‘timer’ and ‘seconds’ to hold the interval ID, and initialize to the value from the duration input field, converted to an integer, respectively.
Updating the Timer Display:
function updateTimerDisplay() {
  const minutes = Math.floor(seconds / 60);
  const secs = seconds % 60;
  timerDisplay.textContent = `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
}
  • Now, let’s create a function called ‘updateTimerDisplay()’ to update the timer display in “MM:SS” format.
  • Additionally, it calculates minutes and seconds from the total ‘seconds’ and updates the ‘timerDisplay’ element’s text content.
Starting the Timer:
function startTimer() {
  if (timer) return; 

  timer = setInterval(() => {
    if (seconds > 0) {
      seconds--;
      updateTimerDisplay();
    } else {
      clearInterval(timer);
      timer = null;
      Sound.play(); // Play the sound when the timer finishes
    }
  }, 1000);
}
  • Create a function ‘startTimer()’ to start the timer and play a sound when the timer reaches zero. It first checks if the timer is already running (to prevent multiple timers).
  • Additionally, by ‘setInterval( () => { ….. }, 1000)’, we execute the provided function every 1000 milliseconds (1 second).
  • Inside the ‘setInterval’ function:
    1.  It checks if ‘seconds’ is greater than zero, it decrements the ‘seconds’ variable by 1, and calls ‘updateTimerDisplay()’ to refresh the timer display.
    2. If ‘seconds’ is zero or less, it means the timer has finished. It clears the interval using ‘clearInterval(timer)’, sets ‘timer’ to ‘null’, and plays the sound by calling ‘Sound.play()’.
Resetting the Timer:
function resetTimer() {
  clearInterval(timer);
  timer = null;
  seconds = parseInt(durationInput.value, 10); // Reset to the value from input
  updateTimerDisplay();
}
  • Now, create a function ‘resetTimer()’, it stops the timer, resets the ‘seconds’ back to the value from the duration input field, and updates the timer display.
Setting the Timer Duration:
function setDuration() {
  seconds = parseInt(durationInput.value, 10); // Set the duration based on user input
  updateTimerDisplay();
}
  • Additionally, create a function ‘setDuration()’ to set the timer based on the user’s input from the duration input field and update the timer display accordingly.
Event Listeners for Buttons:
startBtn.addEventListener('click', startTimer);
resetBtn.addEventListener('click', resetTimer);
setDurationBtn.addEventListener('click', setDuration);
  • Now, add event listeners to the start, reset, and set duration buttons to call the ‘startTimer’, ‘resetTimer’, and ‘setDuration’ functions when the buttons are clicked.
updateTimerDisplay(); 
  • At the end, this call initializes the timer display when the page loads.

So this is your JavaScript code for displaying a timer and when the timer reaches ‘zero’ then the sound will be played.
Now let’s discuss our HTML and CSS code. In our HTML code, we must give one input field to take input from users to set the duration. Also, give a button for a set duration, a start-timer, a reset-timer, and one div for displaying the timer. The most important part is an audio file, do not forget to provide audio in your code.
So below code is a sample HTML code that I used in this tutorial. In your CSS file, provide a style that fits your choice.

<body>
  <div class="container">
    <label for="duration" class="second">Set Timer (seconds):</label>
    <input type="number" id="duration" min="1" value="60" class="input">
    <button id="setDurationBtn" class="range">Set Duration</button>

    <div id="timer" class="time">00:00</div>
    <button id="startBtn" class="start">Start Timer</button>
    <button id="resetBtn" class="reset">Reset Timer</button>
  </div>

  <audio id="Sound" src="sound.mp3"></audio>
  <script src="TimerWithSound.js"></script>
</body>

Output:

Now let’s focus on output:

https://drive.google.com/file/d/1-sW92g2XkRDmrsqQiiMLJHZXct7gUbT8/view?usp=sharing

In the above link, you can see we can set the duration (in seconds) of the Timer and also, you can see the start button, reset button, and timer that starts and when it finishes then sound will be played.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top