Going from static to actual data

As you can see here, functions in TypeScript need to be annotated with the type of the value they return, or just void if none. Our function assesses the current value of both minutes and seconds, and then either decreases their value or just resets it to the initial value. Then this function is called every second by triggering a time interval from the class constructor:

constructor() {
this.minutes = 24;
this.seconds = 59;
setInterval(() => this.tick(), 1000);
}

Here, we spot for the first time in our code an arrow function (also known as a lambda function, fat arrow, and so on), a new syntax for functions brought by ECMAScript 6, which we will cover in more detail in Chapter 3, Introducing TypeScript. The tick function is also marked as private, so it cannot be inspected or executed outside a PomodoroTimerComponent object instance.

So far so good! We have a working Pomodoro timer that countdowns from 25 minutes to 0, and then starts all over again. The problem is that we are replicating code here and there. So, let's refactor everything a little bit to prevent code duplication:

constructor() {
this.reset();
setInterval(() => this.tick(), 1000);
}

reset() {
this.minutes = 24;
this.seconds = 59;
}

private tick() {
if(--this.seconds < 0) {
this.seconds = 59;
if(--this.minutes < 0) {
this.reset();
}
}
}

We have wrapped the initialization (and reset) of minutes and seconds inside our function resetPomodoro, which is called upon instantiating the component or reaching the end of the countdown. Wait a moment though! According to the Pomodoro technique, Pomodoro practitioners are allowed to rest in between Pomodoros or even pause them should an unexpected circumstance get in the way. We need to provide some sort of interactivity so the user can start, pause, and resume the current Pomodoro timer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset