Creating an HTML5 Timer, part 2

Last week, we created a generic timer using canvas and the setInterval function. This week, we will add some audio elements and stylize the application using CSS3.  This timer is going to have an optional ticking sound for each second that elapses and an alarm sound when it has expired.

Adding sounds in HTML5 is done by defining elements with the tag. We’ll need to define a couple of them for our sounds without the controls attribute.







audio tag not supported.











Next we’ll add a helper function to play the sounds.

function playSoundById(elementId) {

document.getElementById(elementId).play();

}

Since the ticking sound is optional, users will be able to turn it off with a button that toggles.



function muteClock() {

clockMuted = !clockMuted;

if (clockMuted == true) {

muteButton.value = "Un-Mute";

return;

}

muteButton.value = "Mute";

}

The last step for the sounds is to make calls to the helper function that we created. The ticking sound should be called from inside the setInterval function and the alarm sound will be called from inside the finish() function.

if (!clockMuted) {

playSoundById('clockTick');

}

playSoundById('alarm');

Last week, we built the interface using a simple html table.  This week, we have removed the table and now rely on CSS to position the elements. This gives us a bit more flexibility for the positioning of elements as well as the styling.















Your browser does not support the canvas tag



































And with a bit of CSS, our timer looks like the following.

[![](/images/content/98b67911-7ac8-4a02-82a5-3cf37a0c29ed.jpg)](/images/content/98b67911-7ac8-4a02-82a5-3cf37a0c29ed.jpg)

You can see the CSS for our timer by [viewing the source of the demo](http://www.yojimbocorp.com/demos/html5_timer2.html), although I would encourage you to experiment with some different styles of your own.