How to create your first Chrome extension
In this article, you'll learn how Chrome extensions work and how to create your own for the first time
Pomodoro is a time management technique developed in the 1980s which uses a timer to break down work into intervals, traditionally 25 minutes in length, separated by short breaks. In this tutorial, you’ll learn how to create such a timer in the browser with JavaScript.
A Pomodoro timer is a simple application that keeps you focused and productive by scheduling work and break sessions consecutively. Traditionally, you have 25-minute focus sessions followed by five-minute breaks and a longer 15-minute break after four consecutive focus sessions.
The Pomodoro timer we’ll be building in this tutorial implements the Pomodoro technique perfectly and tells you exactly when to work and when to take a short break. The basic process is as follows:
You can find a live demo of the completed application here.
You need to have a basic knowledge of HTML, CSS and JavaScript under your belt. Additionally, you need to have Git, Node.js and npm installed on your computer.
Grab the starter files for this tutorial on GitHub. It includes all the markup and styles for the application we’ll be building. You can download the zip file and extract it on your computer, or run the command below in your terminal to clone the repository to your filesystem.
$ git clone https://github.com/Freshman-tech/pomodoro-starter-files.git
Once the repository is downloaded, cd
into it in your terminal:
$ cd pomodoro-starter-files
Next, run the following command to install the browser-sync
dependency which
is used to automatically refresh the browser once a file is changed.
$ npm install
Finally, start the app on http://localhost:3000 using the following command:
$ npm start
At this point, this is what you should see in your browser:
The interface of the application is quite simple. At the top of the page is a progress bar, and following that you have three buttons denoting the three modes of the application. Next, we have the countdown timer and a start button immediately after.
A traditional pomodoro session is 25 minutes, and a short break lasts for five
minutes. A long break (15 minutes) is activated after four consecutive pomodoro
sessions. Let’s turn this information into code by creating a timer
variable
with the following properties:
The next thing we need to do is update the countdown with the appropriate amount of minutes and seconds once any of the three buttons above it is clicked. To do this we need to create an event listener that detects a click on the buttons and a function to switch the mode of the timer appropriately.
Add the following lines of code just below the timer
object in your main.js
file:
Here, we use event delegation to detect a click on any of the mode buttons. The
modeButtons
variable points to the containing element and once a click is
detected on the element, the handleMode()
function is invoked.
Within the handleMode()
function, the value of the data-mode
attribute is
retrieved from the target element. If this attribute does not exist, it means
that the target element was not one of the buttons and the function exits.
Otherwise, a switchMode()
function is invoked with the value of the
data-mode
attribute as its only argument.
Go ahead and create the switchMode()
function just above handleMode()
as
shown below:
The switchMode()
function above adds two new properties to the timer
object.
First, a mode
property is set to the current mode which could be pomodoro
,
shortBreak
or longBreak
. Next, a remainingTime
property is set on the
timer. This is an object which contains three properties of its own:
total
is the total number of seconds remaining. This is set to the number of
minutes of the current mode multiplied by 60. For example, if mode
is
shortBreak
, total
will be set to 300 (the result of 5 ⨉ 60).minutes
is the number of minutes for the mode. For example, a pomodoro
session is 25 minutes.seconds
is always set to zero at the start of a session.Following that, the active
class is removed from all the mode buttons and set
on the one that was clicked, and the background colour of the page is updated.
The use of CSS custom
properties
makes this sort of operation a lot easier.
After all that, an updateClock()
function is invoked. This function is how the
countdown portion of the application is updated. Add it just above the
switchMode()
function as shown below:
The updateClock()
function extracts the value of the minutes
and seconds
properties on the remainingTime
object and pads them with zeros where
necessary so that the number always has a width of two. For example, 8
seconds
will become 08
seconds, but 12
minutes will be left as 12
minutes.
Next, the countdown timer is updated by changing the text content of the relevant elements. At this point, the app should work similarly to the GIF below.
Take a breather, and see the complete code at the end of this step.
The next step is to add the ability to start the timer and countdown to zero.
Declare an interval
variable below timer
:
This variable will be assigned to an instance of the setInterval()
method in a
new startTimer()
function which should be added just above updateClock()
:
Before we can start the timer, we need to get the exact time in the future when
the timer will end. This is achieved by retrieving the timestamp of the current
moment (Date.parse(new Date())
) which is in milliseconds and adding the total
number of milliseconds in the session to it. For reference, 1 second = 1000ms.
This value is then stored in the endTime
variable.
The interval
variable is set to the setInterval()
method which executes the
callback function every 1000 milliseconds (1 second). This callback function
references a getRemainingTime()
function which should be created above
startTimer
as follows:
The function above takes a timestamp argument and finds the difference between
the current time and the end time in milliseconds. This value is stored in the
difference
variable and used to compute the total number of seconds left by
dividing by 1000. The result is subsequently converted to an integer in base 10
through the Number.parseInt()
method and stored in the total
variable.
The minutes
variable contains the number of whole minutes left (if any) and
seconds
is the number of seconds left after whole minutes have been accounted
for. For example, if total
is 230 seconds, minutes
will equal 3 and seconds
will be 50.
Finally, an object containing the values of total
, minutes
, and seconds
is
returned from the function. This corresponds to the structure of the
timer.remainingTime
object seen earlier.
Back to the startTimer()
function, we can see that the return value of
getRemainingTime()
is stored in the timer.remainingTime
property. Next,
updateClock()
is invoked which updates the countdown to the latest value.
Following that, the updated value of the total
property in
timer.remainingTime
is extracted and checked to see if it is less than or
equal to zero. If so, the clearInterval()
method is called with the interval
variable as its only argument and this causes setInterval()
to be cancelled
and the countdown ends.
Let’s call the startTimer()
function once the start button is clicked. Add the
following code just above the modeButtons
variable:
Once the main button is clicked, the value of the data-action
attribute on
the button is stored in an action
variable and checked to see if it’s equal to
“start”. If so, the startTimer()
function is invoked and the countdown begins.
We need to make a small modification to startTimer()
so that the button text
changes to “stop” and the button becomes depressed like a hardware button.
Now, once the countdown timer starts, the value of the button’s data-action
attribute and its text content is changed to “stop”. Also, the active
class is
added to the button causing it to become depressed.
A final thing to do in this section is to ensure that the mode
and remainingTime
properties are set on the timer
object on page load. To do so, we can execute
the switchMode()
property once the DOMContentLoaded
event is fired.
This ensures that the default mode for the timer is pomodoro
and the contents
of timer.remainingTime
is set to the appropriate values for a pomodoro
session. If the above snippet is not present, the program will crash with a
TypeError
if startTimer()
is invoked because timer.remainingTime
will not exist and we’re trying to access the value of the total
property in
that object on the first line of the function.
At this point, you can test the app by setting the timer.pomodoro
property to
1
temporarily and then click the start button to start the countdown to zero.
Remember to return it to 25
before moving on to the next section.
Take a breather, and see the complete code at the end of this step.
The next step is to stop the timer when the stop button is clicked. This button
is the same one used to start the timer. It’s the value of the data-action
attribute on the button that allows us to determine whether to start or stop the
timer.
Add a new stopTimer()
function below startTimer()
as shown below:
In this function, the clearInterval()
method is invoked, causing the
setInterval()
method triggered in startTimer()
to be cancelled so that the
countdown is paused. Next, the value of the button’s data-action
attribute and its text content is changed to “start” and it is returned to its
original form by removing the active
class.
To execute stopTimer()
when data-action
is set to “stop”, modify the
mainButton
event listener as shown below:
Finally, we also need to stop the timer when the mode is changed by clicking any of the three buttons above the countdown:
Take a breather, and see the complete code at the end of this step.
The timer needs to automatically begin a break session at the end of a pomodoro session and vice versa. Additionally, a long break should be triggered after four consecutive pomodoro sessions. This is what we’ll tackle in this section.
First, add a new sessions
property to the timer
object as shown below. This
is how we’ll keep track of the number of pomodoro sessions that have been
completed.
Next, modify the startTimer()
function so that the sessions
property is
incremented at the start of a pomodoro session:
The highlighted line above checks if the current mode is pomodoro
and
increments the timer.sessions
property by 1.
The next step is to auto switch to the next session on completion of the current
one. This also involves a modification to the startTimer()
function:
Once the countdown reaches zero, the switch
statement present above causes the
app to switch to a new break session or pomodoro session depending on the value
of timer.mode
.
In the first case, an if
statement checks if timer.sessions
is divisible by
timer.longBreakInterval
without a remainder and switches to long break mode if
so. Otherwise, a short break session is triggered. The default
case is
executed if a break session is ending which causes a new pomodoro session to
begin.
Finally, startTimer()
is executed again causing the countdown to start again
as before. If you didn’t know already, it’s possible to execute a function from
within itself we’ve just done.
To test this out, you can set the value of the pomodoro
, shortBreak
and
longBreak
properties of the timer
object to 1 temporarily, and observe how
each session leads to the next.
Take a breather, and see the complete code at the end of this step.
In this section, we’ll update the progress bar so that it reflects the progress
of each countdown. The progress bar is aptly represented by the <progress>
element which needs a max
and a value
attribute.
By default, the value
attribute is set to zero indicating that no progress has
been made but the max
attribute is left out. This attribute is essential to
determine what represents 100% completion of a task and it must be greater than
zero.
We can set the max
attribute on the <progress>
element in switchMode()
as
shown below. It’s set to the total amount of seconds in the countdown.
Next, change your updateClock()
function as follows:
Each time updateClock()
is invoked, the value
attribute of the <progress>
element is updated to the result of the remaining amount of seconds subtracted
from the total number of seconds in the session and this causes the progress bar
to update accordingly.
Take a breather, and see the complete code at the end of this step.
For practical reasons, it is beneficial for the countdown and status of the timer to be reflected in the page title. This allows the user to quickly see how many minutes are left in a session without switching tabs.
Modify your updateClock()
function as follows:
Changing the title of the page is as simple as updating the value of the
document.title
property to the desired string. The ternary operator is used to
modify the title depending on if the current mode is set to pomodoro or not.
Take a breather, and see the complete code at the end of this step.
Let’s add some interest to our pomodoro app by playing sounds on certain events. First, we’ll play a sound if the timer is started or stopped and also when transitioning from a pomodoro to a break session (or vice versa).
We’ll tackle the case of starting and stopping the timer first. The relevant
audio file in the project folder is button-sound.mp3
. All we need to do is
create a new audio object using this file, and play the sound each time
mainButton
is clicked. Here’s how:
Let’s continue by playing a sound on the transition from one session to another.
In the index.html
file, we have three audio elements which have a data-sound
attribute corresponding to the three modes available. All we need to do is
select the appropriate one and play it during the transition.
Add the following line below the switch
block in the startTimer()
function:
And that’s all we need to do here. Once a pomodoro session ends and a break session begins, a ringing sound is heard. On the other hand, a “Get back to work” message is played when transitioning to a pomodoro session.
Take a breather, and see the complete code at the end of this step.
Notifications are another way we can draw a user’s attention when transitioning between sessions. Before we can display a notification to the user, we need to ask for permission first. We’ll do this when the page loads. If the request is granted, we can proceed to display notifications otherwise, we won’t be able to.
Modify the document event listener as shown below:
This code will display a notice in your browser asking you to grant notifications permission to the webpage. Ensure to grant this permission before proceeding. Once granted, a test notification will be displayed.
Next, add the following lines below the switch
block in startTimer
to
display a notification when transitioning to a new session:
The above snippet ensures that a new notification is displayed when a new session begins. As demonstrated earlier, the ternary operator is used to set the text in the notification based on the current state of the timer.
Take a breather, and see the complete code at the end of this step.
You’ve reached the end of this tutorial. At this point, you should have a functioning Pomodoro timer application with useful features like sound alerts and notifications. If you have any questions or suggestions, please leave a comment below.
Thanks for reading, and happy coding!
Comments
Ground rules
Please keep your comments relevant to the topic, and respectful. I reserve the right to delete any comments that violate this rule. Feel free to request clarification, ask questions or submit feedback.