A simple Timer class

I’ve been talking about how I am revisiting some of the challenges, with an eye to different approaches and solutions to the same problems. I think there’s a lot of value to be gained by going back to them, looking at a different library, or no library at all. There are many ways to tackle some of these challenges and, at first pass, I know I tend to find the quickest and dirtiest means to “git 'er done.”

Now, though, I’m looking at the Pomodoro Timer challenge. And while this solution might “pass” the challenge, it really doesn’t – the point of that and the others in that section are the use of libraries or frameworks, while this is more geared toward barebones javascript.

Breaking it down to basic components, the most interesting atomic piece (for me) was the Timer itself. All the other functionality, the increment/decrement, the start/stop/reset buttons, whatever, all that stuff is purely there to feed the Timer. So, I decided to try my hand at building an easy-to-use and moderately extensible Timer class. This gave me a chance to tinker with classes, getters/setters, and custom Events. A truly educational experience, let me tell you!

The cool thing about this, the way I was envisioning this, I don’t want to tell the developer how they should use it. I want it to be a piece that fits into a workflow in multiple ways, giving the most flexibility bang for the buck. And so it happened.

I’ve created a Timer class, which can be used in a couple different ways.

  • If you want a pretty DOM node that displays the current timer count, and you want to be able to specify how that timer display text goes, Great! If you want to do all that, and also listen for either per-second tick Events or a completion Event, got that too! In the tick Event, you can also get the current timer value, so you can do something at, say, ten seconds before zero.
  • If, instead, you just want a timer, don’t want to have a DOM node showing, simply cause something to happen in, say, fifteen seconds, cool beans! It’s got that. Simply set it up with an onComplete callback, and tell it what you want to do. Or set up an onTick callback, and at any point you can simply get the current countdown time by myTimer.time to trigger an event so many seconds before zero. Or hey, when the timer completes, you can simply SET a new countdown time by myTimer.time = 400 or whatever, and call myTimer.start() to set another countdown going.

It was a lot of fun to tinker with this, and playing around with it to realize the possibilities. One thing I’m playing with now is having a weird progress thing, almost like an hourglass, that updates every tick with a visual change. Or a Roman numeral countdown timer, cause who doesn’t want to count backwards in XVII?!! lol

Anyway, I would love feedback. I’ve put it up as a codepen project.