Create a 🍅 Pomodoro Timer with HTML, CSS, and Vanilla JavaScript

The Pomodoro technique is a extensively used instrument for rising productiveness. It does this by breaking work intervals into 25 minutes of targeted work adopted by quick breaks. On this tutorial, we are going to create a Pomodoro instrument that permits customers to set a piece interval timer. After the work session, a person can select a 5 or 10 minute break.

Getting Began

Let’s begin by creating the HTML construction for the Pomodoro timer. The timer will function three buttons, particularly:

  • Pomodoro timer button
  • Quick break button
  • Lengthy break button

We will even have a show for every timer length and management buttons for beginning and stopping the timer. 

HTML and CSS

The construction and styling of the timer are comparatively straight-forward; appropriate colours and structure, container components with lessons and IDs for focusing on them correctly. I’ll clarify what all of them are after we dive into the JavaScript, as a result of that’s the place the actual studying occurs on this tutorial!

JavaScript Performance

As I discussed, crucial side of this timer is the JavaScript performance. Begin by getting the IDs of all of the timer button components and assigning them to variables. 

By defining these variables on the high of the file, we’re basically creating them as international variables. JavaScript international variables may be accessed inside features, and this avoids having to redeclare them after we want them.

1
let pomodoro = doc.getElementById("pomodoro-timer");
2
let quick = doc.getElementById("short-timer");
3
let lengthy = doc.getElementById("long-timer");

By default, when a person opens the Pomodoro timer software, we need to present them the 25 minute timer show; so let’s create a perform referred to as showDefaultTimer() that can solely present the Pomodoro timer show and conceal the opposite shows.

1
perform showDefaultTimer() {
2
    pomodoro.fashion.show = "block";
3
    quick.fashion.show = "none";
4
    lengthy.fashion.show = "none";
5
   }
6
   
7
 showDefaultTimer()

Right here, we’re utilizing the CSS show property to vary the visibility of the timer shows. The quick and lengthy show components will likely be hidden, whereas the Pomodoro show will likely be seen. Lastly, we name the showDefaultTimer() perform to make sure that the performance is utilized to the weather when the HTML hundreds. 

Occasion Listeners

Subsequent, nicely create occasion listeners for listening to click on occasions in every timer button. Start by declaring a variable currentTimer and set its worth to null. The currentTimer will designate the presently operating timer. 

1
 let currentTimer =null;

Subsequent, create occasion listeners that will likely be triggered when a person clicks on the buttons. 

1
doc.getElementById("pomodoro-session").addEventListener("click on", perform(){
2
    hideAll();
3
    pomodoro.fashion.show = "block"
4
    currentTimer = pomodoro   
5

6
});
7

8
doc.getElementById("short-break").addEventListener("click on", perform(){
9
    hideAll();
10
    quick.fashion.show = "block"
11
    currentTimer =quick
12
 
13

14
});
15
doc.getElementById("long-break").addEventListener("click on", perform(){
16
    hideAll();
17
    
18
    lengthy.fashion.show = "block"
19
    currentTimer =lengthy
20
    
21
});

The occasion listeners will likely be fired when a person clicks the button timers. For instance, when a person clicks the quick break button, the person will see the 5:00 displayed, and the remainder of the shows will likely be hidden. It’ll additionally set the worth of currentTimer to the quick break timer. 

Cover the Timers

The hideAll() perform will cover all of the timers. Since all of the timers are represented by the identical class identify, “timer-display,” we use doc.querySelectorAll(".timer-display") to pick out and iterate by means of every component and set the fashion.property to none, making the weather invisible. 

1
perform hideAll(){
2
    let timers = doc.querySelectorAll(".timer-display");
3
    timers.forEach(timer=> timer.fashion.show ="none")  
4
};

Begin Timer Performance

JavaScript gives the setInterval() perform that permits us to name a perform after a specified time. The setInterval() perform repeats a perform after a given interval. The syntax appears like this:

1
setInterval(code, delay)

For instance, in our case, we need to decrement a timer by 1 second. Let’s create a startTimer() perform that can take the length of the currentTimer(), begin a countdown, and replace the show with the remaining time.

1
let myInterval = null;
2

3
perform startTimer(timerdisplay){
4
    
5
    timerDuration = timerdisplay.getAttribute("data-duration").break up(":")[0]
6
    let durationinMiliseconds = timerDuration*60*1000;
7
    let endTimestamp = Date.now() + durationinMiliseconds;
8
    
9
}

Let’s break down what is going on right here:

  • let myInterval = null; declares a variable and initializes it to a null worth.
  • Contained in the startTimer() ,perform:timerDuration = timerdisplay.getAttribute("data-duration").break up(":")[0];–  retrieves the length of the currentTimer; for instance, if the component’s length is 25:00, the worth extracted will likely be 25,
  • let durationinMiliseconds = timerDuration*60*1000; – converts the timer length to milliseconds
  • let endTimestamp = Date.now() + durationinMiliseconds; – declares a variable endTimestamp, which is the same as the timestamp when the timer will finish.

Create the Timer

Subsequent, we are going to create our timer utilizing the setInterval() methodology. Our setInterval() methodology will include a perform that can use the time remaining and run each 1 second (1000 milliseconds) till the remaining time runs out. We will even replace our show with the remaining time every second. When the timer reaches 0, we are going to show 00:00 and play an alarm sound.

Replace the startTimer () perform like this:

1
perform startTimer(timerdisplay) {
2
    if (myInterval) {
3
        clearInterval(myInterval);
4
    }
5
    
6
    timerDuration = timerdisplay.getAttribute("data-duration").break up(":")[0];
7
    console.log(timerDuration);
8
    
9
    let durationinmiliseconds = timerDuration * 60 * 1000;
10
    let endTimestamp = Date.now() + durationinmiliseconds;
11
    
12
    
13
    myInterval = setInterval(perform() {
14
        const timeRemaining = new Date(endTimestamp - Date.now());
15
        
16
        
17
        
18
        if (timeRemaining <= 0) {
19
            
20
            clearInterval(myInterval);
21
            timerdisplay.textContent = "00:00";
22
            const alarm = new Audio("https://www.freespecialeffects.co.uk/soundfx/scifi/digital.wav");
23
            alarm.play();
24
        } else {
25
            const minutes = Math.flooring(timeRemaining / 60000);
26
            const seconds = ((timeRemaining % 60000) / 1000).toFixed(0);
27
            const formattedTime = `${minutes}:${seconds.toString().padStart(2, '0')}`;
28
            console.log(formattedTime);
29
            timerdisplay.textContent = formattedTime;
30
        }
31
    }, 1000);
32
}

Contained in the myInterval() perform, we declare a variable timeRemaining that is the same as the time remaining after the timer begins. Then, we verify if the timeRemaining is lower than or equal to 0. If legitimate, we clear the timer with the clearInterval() perform, which takes the interval id as an argument and clears the operating timer. We additionally replace the displayed time to 00:00 and play an audio alarm to tell the person that the timer has reached 0.

If the timeRemaining is bigger than 0, we do the next.

  • const minutes = Math.flooring(timeRemaining / 60000);: converts the remaining time to minutes
  • const minutes = ((timeRemainingpercent60000) /1000).toFixed(0);:  converts the timeRemaining to  seconds  
  • const formattedTime = `${minutes}:${seconds.toString().padStart(2, '0')}`;: codecs the remaining time within the format “MM: SS”
  • timerdisplay.textContent=formattedTime;: updates the textual content content material of the timer show with the formatted time.

When the startTimer() is named, it updates the displayed time each second to create our timer countdown.

Begin Button

For the timer to show a countdown , it must be executed inside the beginning click on occasion listener. Add a click on listener to the beginning button and execute the startTimer() perform. 

1
doc.getElementById("begin").addEventListener("click on", perform () {
2
    if(currentTimer){
3
        startTimer(currentTimer);
4
    }
5
});

 

The occasion listener above will likely be triggered when the beginning button is clicked, and it’ll name the startTimer() perform, which can begin the countdown primarily based on the length handed because the argument.

Fixing Flaws

Our timer is working, however it nonetheless has a flaw; once you begin a brand new timer earlier than the earlier one has ended, the earlier one will nonetheless be operating. To unravel this flaw, we first must verify for an present timer earlier than beginning a brand new one. Contained in the startTimer() perform, add an if assertion that checks if there’s an present timer; if it exists, clear the timer. 

1
perform startTimer(timerdisplay){
2
  if (myInterval) {
3
         clearInterval(myInterval); 
4
        }
5
         // the remainder of the code right here
6

7
    }

To cease the timer when the sop button is clicked, , we name the clearInterval() perform with our Interval id.

1
doc.getElementById("pause").addEventListener("click on", perform () {
2
    if(currentTimer){
3
        clearInterval(myInterval); 
4
        }
5
});

Our Completed Pomodoro Timer!

We’re achieved! See the Pomodoro Timer in motion.

Conclusion

This tutorial has coated learn how to create a primary Pomodoro timer. You need to now be capable to create your personal Pomodoro Timer with extra added performance. Why not take it a step additional and improve the UI? Share your results with us!

 

Trending Merchandise
[product_category category=”trending” per_page=”8″ columns=”2″ orderby=”date” order=”desc”].

We will be happy to hear your thoughts

Leave a reply

MyStudioCafe
Logo
Compare items
  • Total (0)
Compare
0