Inspired by the JavaScript clock I've created a countdown timer. As with the clock, it's a JavaScript module and it's rendered here using a 7-segment font
This version also includes a simple event model: start, stop, paused, resumed, and expired.
Usage
Create an element to hold your timer:
<div id="timer"><div>
Create a script tag to import the module and initialise it:
<script type="module">
import {CountdownTimer} from "./timerModule.min.js";
let duration = 60; // Timer duration in seconds
let options = {}; // Defaults for all options
let timer = new CountdownTimer('timer', duration, options);
timer.start();
</script>
Options
The complete list of options is:
let options = {
showAsMinutes:false, // If true, display minutes & seconds
separator:':', // Displayed between minutes and seconds
padSeconds:2, // Number of seconds digits to display
padMinutes:2 // Number of minutes digits to display
};
Methods
The methods are largely self-explanatory, and with the exception ofsetOptions
take no parameters.
- start() - start timer.
- stop() - stop timer. - Count down cannot be restarted.
- pause() - pause timer. Countdown can be resumed from this point.
- resume() - resume countdown from a previous pause.
- isRunning() - returns a boolean indicating whether the timer is running.
- setOptions(optionList) - set options
For example:
let timer = new CountdownTimer('timer', 60, options);
timer.start();
Events
You can monitor timer events by adding event listeners to the element containing your timer:
document.getElementById('timer').addEventListener('timerStarted', function(){
// Your code here
});
The events are self-explanatory:
- timerStarted
- timerPaused
- timerResumed
- timerStopped
- timerExpired
The downloded file includes a sample page demonstrating the module.
Thanks to Keshikan for the seven-segment font used here.
Questions or comments? Contact me!