-
Notifications
You must be signed in to change notification settings - Fork 0
/
clock.js
94 lines (77 loc) · 1.77 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
(function(global) {
'use strict';
function factory($interval) {
function Clock() {
this.interval = 1;
this.clock = null;
this.ticker = null;
}
Clock.prototype = {
constructor: Clock,
setInterval: _setInterval,
setTicker: setTicker,
start: start,
stop: stop
};
function _setInterval(interval) {
if (typeof interval === 'string') {
this.interval = parseInterval(interval);
} else {
this.interval = interval;
}
}
function setTicker(fn) {
this.ticker = fn;
}
function tick() {
this.ticker();
}
function start() {
this.clock = $interval(tick.bind(this), this.interval);
}
function stop() {
if (this.clock) {
$interval.cancel(this.clock);
this.clock = null;
}
}
var multipliers = {
'h': 36e5,
'm': 6e5,
's': 1e3,
'ms': 1
};
function parseInterval(string) {
var interval = 0;
var valueRe = /\D+/;
var suffixRe = /\d+/;
string.replace(/([0-9]+[hms]{1,2}\s*)/g, function(exp) {
var value = Number(exp.replace(valueRe, '')),
suffix = exp.replace(suffixRe, '');
if (!isNaN(value) && suffix in multipliers) {
interval += value * multipliers[suffix];
}
});
return interval;
}
return Clock;
}
if (typeof global.angular !== 'undefined' && global.angular.module) {
global.angular.module('jsclock', []).factory('Clock', ['$interval', factory]);
} else {
var $interval = function(fn, interval) {
return setInterval(fn, interval);
};
$interval.cancel = clearInterval;
var Clock = factory($interval);
if (typeof define === 'function' && define.amd) {
define(function() {
return Clock;
});
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = Clock;
} else {
global.Clock = Clock;
}
}
})(this);