Creating an HTML 5 Timer, part 1

This week, we will be creating a functional timer using HTML 5 timer elements. For visualization, we will use the canvas element to visualize time elapsed as well as an overlay that displays a message when the time has expired.

As a first step, we will craft the HTML for the interface. At the top of the page, we will display elapsed time followed by a canvas element the represents the elapsed time.

At this point, all that is left to do is to plug in the buttons that we defined earlier. So let’s start with getting the timer running. This function will parse the user input for hours, minutes, and seconds and kick off the timer using HTML5’s setInterval function. The setInterval function will repeatedly be called until it is cleared, so we can take advantage of this to advance our visual representations.

function startClock() {

limit = (parseInt(hInput.value == “” ? “0” : hInput.value) * 3600)

+ (parseInt(mInput.value == “” ? “0” : mInput.value) * 60)

+ parseInt(sInput.value == “” ? “0” : sInput.value);

limit *= 1000;

intervalId = setInterval(function () {

elapsed = elapsed + interval;

wedgeSize = (elapsed / limit) * Math.PI * 2;

updateTime();

var drawX = drawY = radius = size / 2;

var endAngle = startAngle + wedgeSize;

var wedge = canvas.getContext(“2d”);

wedge.beginPath();

wedge.moveTo(drawX, drawY);

wedge.arc(drawX, drawY, radius, startAngle, endAngle, false);

wedge.closePath();

wedge.fillStyle = fillClr;

wedge.fill();

wedge.lineWidth = 0.25;

wedge.strokeStyle = “#eeeeee”;

wedge.stroke();

if (elapsed >= limit) {

clearInterval(intervalId);

finish();

}

}, interval);

}

You should notice a call to an updateTime() function. We’ll need to create this function as it is responsible for the text display of elapsed time.

function updateTime() {

var s,m;

ss += 1;

s = ss < 10 ? ‘0’ + ss : ss;

if (ss > 59) {

ss = 0;

s = ’00’;

mm += 1;

}

m = mm < 10 ? ‘0’ + mm : mm;

if (mm > 59) {

mm = 0;

m = ’00’;

hh += 1;

}

timerElement.value = hh + ‘:’ + m + ‘:’ + s;

}

Once the elapsed time has reached the limit, clearInterval () is called as well as a finish(). The finish() function is something we will need to create. Its purpose for now is to display some text in the overlay.

function finish(){

overlay.innerHTML = “Time is up!”;

}

Since we want our users to be able to pause the timer, we can attach the clearInterval() function to the Pause button.

function pauseClock() {

clearInterval(intervalId);

}

Finally, we will need to create a function for the Reset button. This function will stop the clock, zero out the elapsed time, and re-initialize the canvas.

function resetClock() {

pauseClock();

elapsed = hh = mm = ss = 0;

initClock();

}

You can see the demo in action here. Next week we will add a bit a polish to the interface as well as add some audio indicators for interval updates and an alarm when the time limit is hit.