The Pomodoro technique is a extensively used software for rising productiveness. It does this by breaking work intervals into 25 minutes of centered work adopted by quick breaks. On this tutorial, we are going to create a Pomodoro software 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 characteristic three HTML buttons, specifically:
- Pomodoro timer button
- Brief break button
- Lengthy break button
We will even have a show for every timer period and management buttons for beginning and stopping the timer.
HTML and CSS for the Timer
The construction and styling of the timer are comparatively straight-forward:
- appropriate colours and format
- container components with lessons
- IDs for concentrating on the weather correctly
I’ll clarify what all of them are after we dive into the JavaScript timer design. That’s the place the actual studying occurs on this tutorial!
JavaScript Performance
As I discussed, a very powerful 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 prime of the file, we’re creating them as JavaScript international variables. These could be accessed inside capabilities, which 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 our JavaScript Pomodoro timer utility, we wish to present them the 25 minute timer show.
Let’s create a operate known as showDefaultTimer()
that can solely present the Pomodoro timer show and conceal the opposite ones.
1 |
operate showDefaultTimer() { |
2 |
pomodoro.model.show = "block"; |
3 |
quick.model.show = "none"; |
4 |
lengthy.model.show = "none"; |
5 |
}
|
6 |
|
7 |
showDefaultTimer() |
Right here, we’re utilizing the CSS display property to vary the visibility of the timer shows. The quick and lengthy show components shall be hidden, whereas the Pomodoro show shall be seen.
Lastly, we name the showDefaultTimer()
operate to make sure that the performance is utilized to the weather when the HTML hundreds.
Occasion Listeners
Subsequent, we’ll 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. Because the title suggests, currentTimer
will designate the at present working timer.
1 |
let currentTimer =null; |
Subsequent, create occasion listeners that shall be triggered when a person clicks on the buttons of our JavaScript Pomodoro timer.
1 |
doc.getElementById("pomodoro-session").addEventListener("click on", operate(){ |
2 |
hideAll(); |
3 |
pomodoro.model.show = "block" |
4 |
currentTimer = pomodoro |
5 |
|
6 |
});
|
7 |
|
8 |
doc.getElementById("short-break").addEventListener("click on", operate(){ |
9 |
hideAll(); |
10 |
quick.model.show = "block" |
11 |
currentTimer =quick |
12 |
|
13 |
|
14 |
});
|
15 |
doc.getElementById("long-break").addEventListener("click on", operate(){ |
16 |
hideAll(); |
17 |
|
18 |
lengthy.model.show = "block" |
19 |
currentTimer =lengthy |
20 |
|
21 |
});
|
The occasion listeners shall be fired when a person clicks the timers’ buttons. For instance, when a person clicks the quick break button, they will see the 5:00 show, and the remainder of the shows shall be hidden. It will additionally set the worth of currentTimer
to the quick break timer.
Conceal the Timers
The hideAll()
operate will disguise all of the timers. Since all of the timers are represented by the identical class title, “timer-display,” we use doc.querySelectorAll(".timer-display")
to pick and iterate via every aspect and set the model.property
to none, making the weather invisible.
1 |
operate hideAll(){ |
2 |
let timers = doc.querySelectorAll(".timer-display"); |
3 |
timers.forEach(timer=> timer.model.show ="none") |
4 |
};
|
Begin Timer Performance
JavaScript supplies the setInterval()
operate that permits us to name a operate after a specified time. The setInterval()
operate repeats a operate after a given interval. The syntax within the JavaScript timer seems to be like this:
1 |
setInterval(code, delay) |
For instance, in our case, we wish to decrement a timer by 1 second. Let’s create a startTimer()
operate that can take the period of the currentTimer()
, start a countdown, and replace the show with the remaining time.
1 |
let myInterval = null; |
2 |
|
3 |
operate 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 occurring right here:
-
let myInterval = null;
declares a variable and initializes it to a null worth. - Contained in the startTimer() ,
operate:timerDuration = timerdisplay.getAttribute("data-duration").break up(":")[0];
– retrieves the period of thecurrentTimer
; for instance, if the aspect’s period is 25:00, the worth extracted shall be 25, -
let durationinMiliseconds = timerDuration*60*1000;
– converts the timer period to milliseconds -
let endTimestamp = Date.now() + durationinMiliseconds;
– declares a variableendTimestamp
, which is the same as the timestamp when the timer will finish.
Create the Timer
Subsequent, we be taught make a timer in JavaScript utilizing the setInterval()
technique. Our setInterval()
technique will comprise a operate 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 ()
operate like this:
1 |
operate 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(operate() { |
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.ground(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()
operate, we declare a variable timeRemaining
that is the same as the time left after the timer begins. Then, we test if the timeRemaining
is lower than or equal to 0.
If legitimate, we clear the timer with the clearInterval()
operate, which takes the interval id as an argument and clears the working 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.ground(timeRemaining / 60000);
: converts the remaining time to minutes -
const minutes = ((timeRemainingpercent60000) /1000).toFixed(0);
: converts thetimeRemaining
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()
operate.
1 |
doc.getElementById("begin").addEventListener("click on", operate () { |
2 |
if(currentTimer){ |
3 |
startTimer(currentTimer); |
4 |
}
|
5 |
});
|
The occasion listener above shall be triggered when the beginning button is clicked, and it’ll name the startTimer()
operate, which can begin the countdown based mostly on the period handed because the argument.
Fixing Flaws
Our timer is working, however it nonetheless has a flaw: whenever you begin a brand new timer earlier than the earlier one has ended, the earlier one will nonetheless be working.
To unravel this, we first must test for an current timer earlier than beginning a brand new one.
Contained in the startTimer()
operate, add an if assertion that checks if there’s an current timer; if it exists, clear the timer.
1 |
operate 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()
operate with our Interval ID.
1 |
doc.getElementById("pause").addEventListener("click on", operate () { |
2 |
if(currentTimer){ |
3 |
clearInterval(myInterval); |
4 |
}
|
5 |
});
|
Our Completed Pomodoro Timer!
We’re completed! Now you understand how to make a Pomodoro timer in JavaScript, CSS, and HTML.
See the Pomodoro Timer in motion.
Conclusion
This tutorial has coated make a timer in JavaScript that follows the Pomodoro technique. You need to now be capable of create your individual Pomodoro Timer with extra added performance.
Why not take it a step additional and improve the UI? There is a ton of premium design assets and templates ready for you on the Envato Components library!
Have a look at another cool assets to maintain growing your coding expertise: