-
-
Notifications
You must be signed in to change notification settings - Fork 50
/
jquery.simple.timer.js
269 lines (217 loc) · 7.78 KB
/
jquery.simple.timer.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
/*
* jQuery-Simple-Timer
*
* Creates a countdown timer.
*
* Example:
* $('.timer').startTimer();
*
*/
(function (factory) {
// Using as a CommonJS module
if(typeof module === "object" && typeof module.exports === "object") {
// jQuery must be provided as argument when used
// as a CommonJS module.
//
// For example:
// let $ = require("jquery");
// require("jquery-simple-timer")($);
module.exports = function(jq) {
factory(jq, window, document);
}
} else {
// Using as script tag
//
// For example:
// <script src="jquery.simple.timer.js"></script>
factory(jQuery, window, document);
}
}(function($, window, document, undefined) {
// Polyfill new JS features for older browser
Number.isFinite = Number.isFinite || function(value) {
return typeof value === 'number' && isFinite(value);
}
var timer;
var Timer = function(targetElement){
this._options = {};
this.targetElement = targetElement;
return this;
};
Timer.start = function(userOptions, targetElement){
timer = new Timer(targetElement);
mergeOptions(timer, userOptions);
return timer.start(userOptions);
};
// Writes to `this._options` object so that other
// functions can access it without having to
// pass this object as argument multiple times.
function mergeOptions(timer, opts) {
opts = opts || {};
// Element that will be created for hours, minutes, and seconds.
timer._options.elementContainer = opts.elementContainer || 'div';
var classNames = opts.classNames || {};
timer._options.classNameSeconds = classNames.seconds || 'jst-seconds'
, timer._options.classNameMinutes = classNames.minutes || 'jst-minutes'
, timer._options.classNameHours = classNames.hours || 'jst-hours'
, timer._options.classNameClearDiv = classNames.clearDiv || 'jst-clearDiv'
, timer._options.classNameTimeout = classNames.timeout || 'jst-timeout';
}
Timer.prototype.start = function(options) {
var that = this;
var createSubElements = function(timerBoxElement){
var seconds = document.createElement(that._options.elementContainer);
seconds.className = that._options.classNameSeconds;
var minutes = document.createElement(that._options.elementContainer);
minutes.className = that._options.classNameMinutes;
var hours = document.createElement(that._options.elementContainer);
hours.className = that._options.classNameHours;
var clearElement = document.createElement(that._options.elementContainer);
clearElement.className = that._options.classNameClearDiv;
return timerBoxElement.
append(hours).
append(minutes).
append(seconds).
append(clearElement);
};
this.targetElement.each(function(_index, timerBox) {
var that = this;
var timerBoxElement = $(timerBox);
var cssClassSnapshot = timerBoxElement.attr('class');
timerBoxElement.on('complete', function() {
clearInterval(timerBoxElement.intervalId);
});
timerBoxElement.on('complete', function() {
timerBoxElement.onComplete(timerBoxElement);
});
timerBoxElement.on('complete', function(){
timerBoxElement.addClass(that._options.classNameTimeout);
});
timerBoxElement.on('complete', function(){
if(options && options.loop === true) {
timer.resetTimer(timerBoxElement, options, cssClassSnapshot);
}
});
timerBoxElement.on('pause', function() {
clearInterval(timerBoxElement.intervalId);
timerBoxElement.paused = true;
});
timerBoxElement.on('resume', function() {
timerBoxElement.paused = false;
const secondsLeft = timerBoxElement.data('timeLeft');
const onComplete = timerBoxElement.onComplete;
that.startCountdown(timerBoxElement, { secondsLeft, onComplete });
});
createSubElements(timerBoxElement);
return this.startCountdown(timerBoxElement, options);
}.bind(this));
};
/**
* Resets timer and add css class 'loop' to indicate the timer is in a loop.
* $timerBox {jQuery object} - The timer element
* options {object} - The options for the timer
* css - The original css of the element
*/
Timer.prototype.resetTimer = function($timerBox, options, css) {
var interval = 0;
if(options.loopInterval) {
interval = parseInt(options.loopInterval, 10) * 1000;
}
setTimeout(function() {
$timerBox.trigger('reset');
$timerBox.attr('class', css + ' loop');
timer.startCountdown($timerBox, options);
}, interval);
}
Timer.prototype.fetchSecondsLeft = function(element){
var secondsLeft = element.data('seconds-left');
var minutesLeft = element.data('minutes-left');
if(Number.isFinite(secondsLeft)){
return parseInt(secondsLeft, 10);
} else if(Number.isFinite(minutesLeft)) {
return parseFloat(minutesLeft) * 60;
}else {
throw 'Missing time data';
}
};
Timer.prototype.startCountdown = function(element, options) {
options = options || {};
var intervalId = null;
var defaultComplete = function(){
clearInterval(intervalId);
return this.clearTimer(element);
}.bind(this);
element.onComplete = options.onComplete || defaultComplete;
element.allowPause = options.allowPause || false;
if(element.allowPause){
element.on('click', function() {
if(element.paused){
element.trigger('resume');
}else{
element.trigger('pause');
}
});
}
var secondsLeft = options.secondsLeft || this.fetchSecondsLeft(element);
var refreshRate = options.refreshRate || 1000;
var endTime = secondsLeft + this.currentTime();
var timeLeft = endTime - this.currentTime();
this.setFinalValue(this.formatTimeLeft(timeLeft), element);
intervalId = setInterval((function() {
timeLeft = endTime - this.currentTime();
// When timer has been idle and only resumed past timeout,
// then we immediatelly complete the timer.
if(timeLeft < 0 ){
timeLeft = 0;
}
element.data('timeLeft', timeLeft);
this.setFinalValue(this.formatTimeLeft(timeLeft), element);
}.bind(this)), refreshRate);
element.intervalId = intervalId;
};
Timer.prototype.clearTimer = function(element){
element.find('.jst-seconds').text('00');
element.find('.jst-minutes').text('00:');
element.find('.jst-hours').text('00:');
};
Timer.prototype.currentTime = function() {
return Math.round((new Date()).getTime() / 1000);
};
Timer.prototype.formatTimeLeft = function(timeLeft) {
var lpad = function(n, width) {
width = width || 2;
n = n + '';
var padded = null;
if (n.length >= width) {
padded = n;
} else {
padded = Array(width - n.length + 1).join(0) + n;
}
return padded;
};
var hours = Math.floor(timeLeft / 3600);
timeLeft -= hours * 3600;
var minutes = Math.floor(timeLeft / 60);
timeLeft -= minutes * 60;
var seconds = parseInt(timeLeft % 60, 10);
if (+hours === 0 && +minutes === 0 && +seconds === 0) {
return [];
} else {
return [lpad(hours), lpad(minutes), lpad(seconds)];
}
};
Timer.prototype.setFinalValue = function(finalValues, element) {
if(finalValues.length === 0){
this.clearTimer(element);
element.trigger('complete');
return false;
}
element.find('.' + this._options.classNameSeconds).text(finalValues.pop());
element.find('.' + this._options.classNameMinutes).text(finalValues.pop() + ':');
element.find('.' + this._options.classNameHours).text(finalValues.pop() + ':');
};
$.fn.startTimer = function(options) {
this.TimerObject = Timer;
Timer.start(options, this);
return this;
};
}));