-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclock.js
55 lines (51 loc) · 1.62 KB
/
clock.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
Number.prototype.pad = function(size) {
let s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
}
Clock = function(selector, options) {
this.tickId; // Timeout function
this.selector = selector;
this.options = options || {};
this._parent = $(selector)
// State
this.hrs = null;
this.mins = null;
let html = `<span class="clk-hrs"></span><span class="clk-sep">:</span><span class="clk-mins"></span><span class="clk-sep">:</span><span class="clk-secs"></span><span class="clk-ampm"></span>`;
this._parent.html(html);
}
Clock.prototype.tick = function(force_update = false) {
let now = new Date();
hours = now.getHours();
mins = now.getMinutes();
ampm = "";
if (this.options["12hr"] === true) {
if (hours > 11) {
ampm = "pm";
} else {
ampm = "am";
}
if (hours > 12) {
hours = hours - 12;
}
}
// Only update hours and minutes if they've changed
if (hours !== this.hrs || force_update) {
this._parent.find(".clk-hrs").text(`${(hours).pad(2)}`);
this._parent.find(".clk-ampm").text(" " + ampm);
this.hrs = hours;
}
if (mins !== this.mins || force_update) {
this._parent.find(".clk-mins").text(`${(mins).pad(2)}`);
this.mins = mins;
}
this._parent.find(".clk-secs").text(`${(now.getSeconds()).pad(2)}`);
}
Clock.prototype.startTick = function() {
let _this = this;
_this.tick();
this.tickId = setInterval(function() { _this.tick(); }, 1000);
}
Clock.prototype.stopTick = function() {
clearInterval(this.tickId);
}