Really implement a chronometer
[cascardo/pomo.git] / pomo.js
1 MILS_PER_SECOND = 1000;
2 MILS_PER_MINUTE = 60 * MILS_PER_SECOND;
3 MILS_PER_HOUR = 60 * MILS_PER_MINUTE;
4
5 function Pomo() {
6         var p = this;
7         this.pomo = document.getElementById("pomo");
8         this.start = function() {
9                 this.date = new Date();
10                 setTimeout(function() {
11                                 p.update();
12                         }, 500);
13         };
14         this.prefix = function(i) {
15                 if (i < 10) {
16                         i = "0" + i;
17                 }
18                 return i;
19         }
20         this.update = function() {
21                 var now = new Date();
22                 var mils = this.date.getTime() + 25 * MILS_PER_MINUTE - now.getTime();
23                 if (mils < 0) {
24                         this.alarm();
25                         mils = 0;
26                 } else {
27                         setTimeout(function() {
28                                         p.update();
29                                 }, 500);
30                 }
31                 var hours = Math.floor(mils / MILS_PER_HOUR);
32                 mils -= hours * MILS_PER_HOUR;
33                 var minutes = Math.floor(mils / MILS_PER_MINUTE);
34                 mils -= minutes * MILS_PER_MINUTE;
35                 var seconds = Math.floor(mils / MILS_PER_SECOND);
36                 var s_date = this.prefix(hours) + ":" + this.prefix(minutes) + ":" + this.prefix(seconds);
37                 this.pomo.innerHTML = s_date;
38         };
39         this.alarm = function() {
40                 var audio = document.getElementById("alarm");
41                 audio.play();
42         }
43 }
44
45 var pomo = new Pomo();
46 pomo.start();