jQuery: stopwatch & countdown
This is a basic stopwatch plugin to run with jquery. Start timer, pause it, stop it or reset it. Will add countdown function soon.
by Mike Gifford
HTML
<div>
<h1>Countdown</h1>
<span id="cd_h">00</span>: <span id="cd_m">00</span>: <span id="cd_s">00</span>: <span id="cd_ms">00</span>
<br/>
<br/>
<input type="button" value="Start" id="cd_start" />
<input type="button" value="Pause" id="cd_pause" />
<input type="button" value="Stop" id="cd_stop" />
<input type="button" value="Reset" id="cd_reset" />
<br/>
<br/>
<input type="text" value="900" id="cd_seconds" />secs
<br/>
<br/> <span id="cd_status">Idle</span>
</div>
CSS
input {
padding:4px;
}
input[type="text"] {
width:50px;
text-align:center;
}
div {
font-family:Arial, Verdana;
font-size:12px;
width:360px;
background-color:#f2f2f2;
padding:16px;
border:solid 1px #e5e5e5;
text-align:center;
margin:0 0 16px 0;
}
div span:last-child {
color:green;
}
h1 {
font-size:14px;
margin:0 0 8px 0;
}
JavaScript
/*
JQUERY: STOPWATCH & COUNTDOWN
This is a basic stopwatch & countdown plugin to run with jquery. Start timer, pause it, stop it or reset it. Same behaviour with the countdown besides you need to input the countdown value in seconds first. At the end of the countdown a callback function is invoked.
Any questions, suggestions? marc.fuehnen(at)gmail.com
*/
$(document).ready(function () {
(function ($) {
$.extend({
APP: {
formatTimer: function (a) {
if (a < 10) {
a = '0' + a;
}
return a;
},
startTimer: function (dir) {
var a;
// save type
$.APP.dir = dir;
// get current date
$.APP.d1 = new Date();
switch ($.APP.state) {
case 'pause':
// resume timer
// get current timestamp (for calculations) and
// substract time difference between pause and now
$.APP.t1 = $.APP.d1.getTime() - $.APP.td;
break;
default:
// get current timestamp (for calculations)
$.APP.t1 = $.APP.d1.getTime();
// if countdown add ms based on seconds in textfield
if ($.APP.dir === 'cd') {
$.APP.t1 += parseInt($('#cd_seconds').val()) * 1000;
}
break;
}
// reset state
$.APP.state = 'alive';
$('#' + $.APP.dir + '_status').html('Running');
// start loop
$.APP.loopTimer();
},
...