2,399 Views

Developing a Pomodoro Timer in Ionic 2

Pomodoro Technique is a time management technique that uses a timer to break down work into short intervals separated by short breaks. It helps get through distraction with intense focused work.

In this tutorial we will make a pomodoro timer using Ionic 2, so let’s get started.

You can view the final result of this tutorial is hosted in github repo

You can view the final result of what we will be building in this tutorial in the following video

Requirements

Before you begin this tutorial you need to install ionic 2. If you have not already installed ionic 2 please refer to our getting started tutorial.

Create a new project

$ ionic start MyPomodoro blank --v2

Verify your project is properly created by serving it to your browser

$ cd MyPomodoro
$ ionic serve

If your project is properly created and configured, then you should following page when you visit http://localhost:8100

ionic-serve-blank-result.png

Now we are ready to begin working with our application. Open the project folder in your favourite text editor or IDE, I prefer to use Atom as mine.

Now let us create a new timer component using ionic CLI

$ ionic g component timer

This command should generate following three files

  • MyPomodoro/src/components/timer/timer.html
  • MyPomodoro/src/components/timer/timer.scss
  • MyPomodoro/src/components/timer/timer.ts

Open timer.html in your text editor and change the code to following

<div>
 <ion-item class="no-bottom-border item">
 <h1 text-center color="primary" class="timer-button timer-text">00:20:36</h1>
 </ion-item>
 </div>

Open src/app/app.module.ts

import the timer component below import {HomePage} with the code

import {TimerComponent} from “../components/timer/timer”;

And in declarations array add TimerComponent

Now, your app.module.ts should look like

import { NgModule, ErrorHandler } from '@angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import {TimerComponent} from "../components/timer/timer";
@NgModule({
 declarations: [
 MyApp,
 HomePage,
 TimerComponent
 ],
 imports: [
 IonicModule.forRoot(MyApp)
 ],
 bootstrap: [IonicApp],
 entryComponents: [
 MyApp,
 HomePage
 ],
 providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}

Open, src/pages/home/home.ts

import TimerComponent as you did in app.module.ts

open src/pages/home/home.html and change title from Ionic Blank to My Pomodoro

and change the content of <ion-content> tag to following

<timer></timer>

By now, the browser page you served using ionic serve should be automatically reloaded, if not reload the page yourself and you should see the following output

Now lets make a timer interface to save our timer data

Create src/components/timer/PTimer.ts and add following code

export interface PTimer {
 time: number;
 timeRemaining: number;
 runTimer: boolean;
 hasStarted: boolean;
 hasFinished: boolean;
 displayTime: string;
}

Open src/components/timer/timer.ts and change the content of timer.ts to the following

import { Component } from '@angular/core';
import {PTimer} from "./ptimer";
/*
 Generated class for the Timer component.

See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
 for more info on Angular 2 Components.
*/
@Component({
 selector: 'timer',
 templateUrl: 'timer.html'
})
export class TimerComponent {

private timeInSeconds: number;
 public timer: PTimer;
 constructor() {
 }

ngOnInit() {
 this.initTimer();
 }

hasFinished() {
 return this.timer.hasFinished;
 }
 initTimer() {
 if (!this.timeInSeconds) { this.timeInSeconds = 1500; }

this.timer = <PTimer>{
 time: this.timeInSeconds,
 runTimer: false,
 hasStarted: false,
 hasFinished: false,
 timeRemaining: this.timeInSeconds
 };
 this.timer.displayTime = this.getSecondsAsDigitalClock(this.timer.timeRemaining);
 }

getSecondsAsDigitalClock(inputSeconds: number) {
 var sec_num = parseInt(inputSeconds.toString(), 10); // don't forget the second param
 var hours = Math.floor(sec_num / 3600);
 var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
 var seconds = sec_num - (hours * 3600) - (minutes * 60);
 var hoursString = '';
 var minutesString = '';
 var secondsString = '';
 hoursString = (hours < 10) ? "0" + hours : hours.toString();
 minutesString = (minutes < 10) ? "0" + minutes : minutes.toString();
 secondsString = (seconds < 10) ? "0" + seconds : seconds.toString();
 return hoursString + ':' + minutesString + ':' + secondsString;
 }

}

In this code, first we have imported PTimer interface and created a timer object of type PTimer. Then we have called initTimer() function to initialize timer object with default time of 20 (in seconds). The initTimer() function calls getSecondsAsDigitalClock() function which turns given seconds into time string consisting of hours, minutes and seconds. Be sure to check your browser to verify the code is working and you are seeing the output.

Change the contents of timer.html to the following

<div>
 <ion-item class="no-bottom-border item">
 <h1 text-center color="primary" class="timer-button timer-text">{{timer.displayTime}}</h1>
 </ion-item>
</div>

Get the Clock ticking

Still working with timer.ts file, add a function called startTimer() as

startTimer() {
 this.timer.hasStarted = true;
 this.timer.runTimer = true;
 this.timerTick();
 }

Now lets add the timerTick() function called by startTimer() function. This is the function that will get our clock ticking

timerTick() {
 setTimeout(() => {

if (!this.timer.runTimer) { return; }
 this.timer.timeRemaining--;
 this.timer.displayTime = this.getSecondsAsDigitalClock(this.timer.timeRemaining);
 if (this.timer.timeRemaining > 0) {
 this.timerTick();
 }
 else {
 this.timer.hasFinished = true;
 }
 }, 1000);
 }

To view that the timer is ticking, call startTimer() function within our initTimer() function at the end. This should get your timer ticking and should stop when it’s 0.

Start, Pause, Resume and Reset

It’s no fun if you cannot play with the timer object so add following three functions in timer.ts

hasFinished() {
 return this.timer.hasFinished;
 }
 pauseTimer() {
 this.timer.runTimer = false;
 }
resumeTimer() {
 this.startTimer();
 }

Let’s add buttons in timer.html to make these functions work

<ion-fab bottom left *ngIf="timer.runTimer && timer.hasStarted && !timer.hasFinished">
 <button ion-fab color="primary" (click)="pauseTimer()">
 <ion-icon name="pause"></ion-icon>
 </button>
 </ion-fab>
 <ion-fab bottom left *ngIf="!timer.runTimer && timer.hasStarted && !timer.hasFinished"> 
 <button ion-fab color="primary" (click)="resumeTimer()">
<ion-icon name="play"></ion-icon>
</button>
 </ion-fab>
 <ion-fab bottom left *ngIf="!timer.hasStarted"> //show only if timer has not started
 <button ion-fab color="primary" (click)="startTimer()" item-right>
<ion-icon name="play"></ion-icon>
</button>
 </ion-fab>

<ion-fab bottom right *ngIf="!timer.runTimer && (timer.hasStarted || timer.hasFinished) || timer.hasFinished">
 <button ion-fab color="danger" (click)="initTimer()" item-left>
 <ion-icon name="refresh"></ion-icon>
 </button>
 </ion-fab>

These are ionic fab buttons with icons to allow user to start, pause, resume and reset timer clock. Now just remove the startTimer() function call from initTimer() function and you are good to go.

Now, you should be able to start, pause, resume and reset the timer clock.

Please let us know in comments if there are any problem.

Related Posts

Android Launcher App in React Native

A simple custom Android launcher app built with React Native. Find in GitHub A custom Android Launcher made with ReactNativehttps://github.com/lohanidamodar/RNLauncher5 forks.19 stars.0 open […]

This post is trending.

Beautiful Timeline Component in Ionic 3

In this tutorial we will be building a beautiful timeline component to display any suitable content from blog posts to comments or […]

%d bloggers like this: