DEV Community

loading...
Cover image for Build a Pomodoro timer using JavaScript

Build a Pomodoro timer using JavaScript

Fahad Hassan
Junior Full-Stack-Web-Developer and UI&UX designer at DevNation
・4 min read

Let's understand how can we create a Pomodoro timer by using JavaScript

To get complete code visit: GitHub

What is a Pomodoro Timer?

Pomodoro Timer is a technique that uses a timer to break down work into intervals. Traditionally 25 minutes in length separated by short breaks. The image below is an example of a Pomodoro timer.

Let's get started!

Task# 1

We need to decrease the time of the timer starting from 25 minutes to 0
As we know, in a Pomodoro timer every work session will be of 25 minutes and after every 25 minutes there will be a break session, let suppose break time is 5 minutes

workDuration = 25
breakDuration = 5
seconds = 60
Enter fullscreen mode Exit fullscreen mode

Our first task is to decrease the time by one second seconds = seconds - 1 on every clock second.

We also need to keep in mind that when the seconds become :00 we need to reinitialized seconds = 60 and with this, we also need to decrement the minutes by 1 workDuration = workDuration - 1;

let's arrange the code by writing a function RemainingTime()

workMinutes = workDuration - 1           //25 = 24:59
breakMinutes = breakDuration - 1        //5 = 4:59 
let RemainingTime = () =>{
    seconds = seconds - 1
    if(seconds === 0){
        workMinutes = workMinutes - 1
        seconds = 60
}
}
Enter fullscreen mode Exit fullscreen mode

Now we are done with Task# 1. But there is a problem!

The RemainingTime() function will execute only once when we call it, so to fix this problem we need to call this function on every clock second.

Task 2

To call a function multiple times there is a built-in method in JavaScript named as setInterval

setInterval() method is used to execute a specified function multiple times at set time intervals specified in milliseconds (1000ms = 1second). We have to pass to arguments to this method

setInterval(your_fucntion_name , specified_time)
Enter fullscreen mode Exit fullscreen mode

As we want to call our function on every clock second so our arguments to the set interval method will be

setInterval(RemainingTime,1000)
Enter fullscreen mode Exit fullscreen mode

Now the code will look like

let RemainingTime = () =>{
    seconds = seconds - 1
    if(seconds === 0){
        workMinutes = workMinutes - 1
        seconds = 60
}
}
let timer = setInterval(RemainingTime , 1000)
Enter fullscreen mode Exit fullscreen mode

Now it make sense , Our function will be called on every clock second
If you noticed we are not dealing with the break time in the above function.

What if the workMinutes become -ve by continuously decrement in workMinutes?

When the work duration will be over (workMinutes become -ve) we need to start the break session (breakDuration = 5)

For this purpose we have to add some conditions in our code

let RemainingTime = () =>{
    seconds = seconds - 1
    if(seconds === 0){
        workMinutes = workMinutes - 1
        if(workMinutes === -1){
             workMinutes = breakMinutes
}
        seconds = 60
}
}
let timer = setInterval(RemainingTime , 1000)
Enter fullscreen mode Exit fullscreen mode

In the above code when the workMinutes become -ve(or less than 0) then breakMinutes will be assigned to workMinutes
This condition causes the code to start a session of break(5 minutes session) when the workMinutes become over

Let understand this by an example

- let we have workMinutes = 4:59 and we have breakMinutes = 1:59
- Now start decreasing the workMinutes
  (4:59,4:58,4:57,4:56 ..... 0:05,0:04,0:03,0:02,0:01,0:00,-1:59)
  in the above line when the workMinutes become -ve(-1:59)
- We will assign breakMinute to workMinutes then workMinutes 
  become workMinutes = 1:59
- Now when we do this workMinutes will never goes to -ve value. 
- However when it will become -ve It will start a break session 
  of specified time (e.g: 1:59) and will start decreasing the 
  break time which is (1:59,1:59,1:57 ..... 0:00)
Enter fullscreen mode Exit fullscreen mode

Now if you noticed, what will we do when the break session will over?

if we do not deal with this, the timer will again go to -ve time and will start decreasing that time.

Task 3

The solution to the above problem is, we have to again start the work session when the break session become 0:00 or turned to the -ve timer.

To do this we have to add another condition that will help us regarding this.

Before doing this, I want you to consider that we are also dealing with the break session after every work session. So we need a break session after every work session.

We just have to follow the following sequence for a continuous timer.

  • After every work session, there will be a break session
  • After the break session, there will be always a work session

We need to count the break session so that by using breakCount we can be able to check the turn of the break session

To follow this sequence in our code we need to just put some conditions and these conditions will check whether there is time for work session time or break session time.

let have a look at the code to understand the scenario.

breakCount = 0
let RemainingTime = () =>{
    seconds = seconds - 1
    if(seconds === 0){
        workMinutes = workMinutes - 1
        if(workMinutes === -1){
            if(breakCount % 2 === 0){
               workMinutes = breakMinutes;
               breakCount++
            }else{
               workMinutes = workDuration - 1
               breakCount++
            }
          }
        seconds = 60
      }
}
let timer = setInterval(RemainingTime , 1000)
Enter fullscreen mode Exit fullscreen mode

Hurry! our Pomodoro timer is ready

In the end when we want to stop our timer. For this, we just have to stop the setInterval() method so that it stops the function calling.

To do this we just have to use the built-in method of JavaScript named as clearInterval() method which is used to clear or stop the set Intervals in JavaScript.

clearInterval(timer)
Enter fullscreen mode Exit fullscreen mode

You have to add an event listener on your stop button. When the stop button is clicked, you need to call the method clearInterval(timer) which will stop the timer completely.

Conclusion

Thanks for reading this article!
want to ask something? hit a comment below!

Discussion (2)

Collapse
lukeshiru profile image
LUKE知る

If you want a super precise interval (the native is not precise with all browsers), you can do this:

export const animationInterval = signal => ms => callback => {
  const start = document.timeline
    ? document.timeline.currentTime
    : performance.now();

  const scheduleFrame = time => {
    const elapsed = time - start;
    const roundedElapsed = Math.round(elapsed / ms) * ms;
    const targetNext = start + roundedElapsed + ms;
    const delay = targetNext - performance.now();
    return setTimeout(() => requestAnimationFrame(frame), delay);
  };

  const frame = time => {
    if (!signal.aborted) {
      callback(time);
      scheduleFrame(time);
    }
  };

  scheduleFrame(start);
};
Enter fullscreen mode Exit fullscreen mode

And the usage:

import { animationInterval } from "./animationInterval.js";

const controller = new AbortController();
const intervalWithController = animationInterval(controller);
const oneSecondInterval = intervalWithController(1000);

// We log every second
oneSecondInterval(console.log);

// Stop the interval
controller.abort();
Enter fullscreen mode Exit fullscreen mode

This is taken from a really interesting video from the Chrome Developers Channel:

Cheers! :D

Collapse
fahadhassan1213 profile image
Fahad Hassan Author

Ahan!
Thanks for your precious advice.
I will do this

Forem Open with the Forem app