-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.js
613 lines (513 loc) · 17.7 KB
/
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/**
* easytimer.js
* Generated: 2019-07-22
* Version: 4.0.1
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.easytimer = {}));
}(this, function (exports) { 'use strict';
function _typeof(obj) {
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function (obj) {
return typeof obj;
};
} else {
_typeof = function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
function leftPadding(string, padLength, character) {
var i;
var characters = '';
string = typeof string === 'number' ? String(string) : string;
if (string.length > padLength) {
return string;
}
for (i = 0; i < padLength; i = i + 1) {
characters += String(character);
}
return (characters + string).slice(-characters.length);
}
function TimeCounter() {
this.secondTenths = 0;
this.seconds = 0;
this.minutes = 0;
this.hours = 0;
this.days = 0;
/**
* [toString convert the counted values on a string]
* @param {array} units [array with the units to display]
* @param {string} separator [separator of the units]
* @param {number} leftZeroPadding [number of zero padding]
* @return {string} [result string]
*/
this.toString = function () {
var units = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['hours', 'minutes', 'seconds'];
var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ':';
var leftZeroPadding = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2;
units = units || ['hours', 'minutes', 'seconds'];
separator = separator || ':';
leftZeroPadding = leftZeroPadding || 2;
var stringTime;
var arrayTime = [];
var i;
for (i = 0; i < units.length; i = i + 1) {
if (this[units[i]] !== undefined) {
if (units[i] === 'secondTenths') {
arrayTime.push(this[units[i]]);
} else {
arrayTime.push(leftPadding(this[units[i]], leftZeroPadding, '0'));
}
}
}
stringTime = arrayTime.join(separator);
return stringTime;
};
}
/*
* Polyfill por IE9, IE10 and IE11
*/
var CustomEvent$1 = typeof window !== 'undefined' ? window.CustomEvent : undefined;
if (typeof window !== 'undefined' && typeof CustomEvent$1 !== 'function') {
CustomEvent$1 = function CustomEvent(event, params) {
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent$1.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent$1;
}
/*
* General functions, variables and constants
*/
var SECOND_TENTHS_PER_SECOND = 10;
var SECONDS_PER_MINUTE = 60;
var MINUTES_PER_HOUR = 60;
var HOURS_PER_DAY = 24;
var SECOND_TENTHS_POSITION = 0;
var SECONDS_POSITION = 1;
var MINUTES_POSITION = 2;
var HOURS_POSITION = 3;
var DAYS_POSITION = 4;
var SECOND_TENTHS = 'secondTenths';
var SECONDS = 'seconds';
var MINUTES = 'minutes';
var HOURS = 'hours';
var DAYS = 'days';
var VALID_INPUT_VALUES = [SECOND_TENTHS, SECONDS, MINUTES, HOURS, DAYS];
var unitsInMilliseconds = {
secondTenths: 100,
seconds: 1000,
minutes: 60000,
hours: 3600000,
days: 86400000
};
var groupedUnits = {
secondTenths: SECOND_TENTHS_PER_SECOND,
seconds: SECONDS_PER_MINUTE,
minutes: MINUTES_PER_HOUR,
hours: HOURS_PER_DAY
};
var events = typeof module !== 'undefined' && module.exports && typeof require === 'function' ? require('events') : undefined;
function hasDOM() {
return typeof document !== 'undefined';
}
function hasEventEmitter() {
return events;
}
function mod(number, module) {
return (number % module + module) % module;
}
/**
* [Timer Timer/Chronometer/Countdown compatible with AMD and NodeJS.
* Can update time values with different time intervals: tenth of seconds,
* seconds, minutes and hours.]
*/
function Timer() {
/*
* PRIVATE variables and Functions
*/
var counters = new TimeCounter();
var totalCounters = new TimeCounter();
var intervalId;
var eventEmitter = hasDOM() ? document.createElement('span') : hasEventEmitter() ? new events.EventEmitter() : undefined;
var running = false;
var paused = false;
var precision;
var timerTypeFactor;
var customCallback;
var timerConfig = {};
var currentParams;
var targetValues;
var startValues;
var countdown;
var startingDate;
var targetDate;
var eventData = {
detail: {
timer: this
}
};
function updateCounters(precision, roundedValue) {
totalCounters[precision] = roundedValue;
if (precision === DAYS) {
counters[precision] = roundedValue;
} else if (roundedValue >= 0) {
counters[precision] = mod(roundedValue, groupedUnits[precision]);
} else {
counters[precision] = groupedUnits[precision] - mod(roundedValue, groupedUnits[precision]);
}
}
function updateDays(value) {
return updateUnitByPrecision(value, DAYS);
}
function updateHours(value) {
return updateUnitByPrecision(value, HOURS);
}
function updateMinutes(value) {
return updateUnitByPrecision(value, MINUTES);
}
function updateSeconds(value) {
return updateUnitByPrecision(value, SECONDS);
}
function updateSecondTenths(value) {
return updateUnitByPrecision(value, SECOND_TENTHS);
}
function updateUnitByPrecision(value, precision) {
var previousValue = totalCounters[precision];
updateCounters(precision, calculateIntegerUnitQuotient(value, unitsInMilliseconds[precision]));
return totalCounters[precision] !== previousValue;
}
function stopTimerAndResetCounters() {
stopTimer();
resetCounters();
}
function stopTimer() {
clearInterval(intervalId);
intervalId = undefined;
running = false;
paused = false;
}
function setParamsAndStartTimer(params) {
if (!isPaused()) {
setParams(params);
} else {
startingDate = calculateStartingDate();
targetValues = setTarget(currentParams.target);
}
startTimer();
}
function startTimer() {
var interval = unitsInMilliseconds[precision];
if (isTargetAchieved(roundTimestamp(Date.now()))) {
return;
}
intervalId = setInterval(updateTimerAndDispatchEvents, interval);
running = true;
paused = false;
}
function calculateStartingDate() {
return roundTimestamp(Date.now()) - totalCounters.secondTenths * unitsInMilliseconds[SECOND_TENTHS] * timerTypeFactor;
}
function updateTimerAndDispatchEvents() {
var currentTime = roundTimestamp(Date.now());
var valuesUpdated = updateTimer();
dispatchEvents(valuesUpdated);
customCallback(eventData.detail.timer);
if (isTargetAchieved(currentTime)) {
stop();
dispatchEvent('targetAchieved', eventData);
}
}
function updateTimer() {
var currentTime = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : roundTimestamp(Date.now());
var elapsedTime = timerTypeFactor > 0 ? currentTime - startingDate : startingDate - currentTime;
var valuesUpdated = {};
valuesUpdated[SECOND_TENTHS] = updateSecondTenths(elapsedTime);
valuesUpdated[SECONDS] = updateSeconds(elapsedTime);
valuesUpdated[MINUTES] = updateMinutes(elapsedTime);
valuesUpdated[HOURS] = updateHours(elapsedTime);
valuesUpdated[DAYS] = updateDays(elapsedTime);
return valuesUpdated;
}
function roundTimestamp(timestamp) {
return Math.floor(timestamp / unitsInMilliseconds[precision]) * unitsInMilliseconds[precision];
}
function dispatchEvents(valuesUpdated) {
if (valuesUpdated[SECOND_TENTHS]) {
dispatchEvent('secondTenthsUpdated', eventData);
}
if (valuesUpdated[SECONDS]) {
dispatchEvent('secondsUpdated', eventData);
}
if (valuesUpdated[MINUTES]) {
dispatchEvent('minutesUpdated', eventData);
}
if (valuesUpdated[HOURS]) {
dispatchEvent('hoursUpdated', eventData);
}
if (valuesUpdated[DAYS]) {
dispatchEvent('daysUpdated', eventData);
}
}
function isTargetAchieved(currentDate) {
return targetValues instanceof Array && currentDate >= targetDate;
}
function resetCounters() {
for (var counter in counters) {
if (counters.hasOwnProperty(counter) && typeof counters[counter] === 'number') {
counters[counter] = 0;
}
}
for (var _counter in totalCounters) {
if (totalCounters.hasOwnProperty(_counter) && typeof totalCounters[_counter] === 'number') {
totalCounters[_counter] = 0;
}
}
}
function setParams(params) {
params = params || {};
precision = checkPrecision(params.precision);
customCallback = typeof params.callback === 'function' ? params.callback : function () {};
countdown = params.countdown === true;
timerTypeFactor = countdown === true ? -1 : 1;
if (_typeof(params.startValues) === 'object') {
setStartValues(params.startValues);
} else {
startValues = null;
}
startingDate = calculateStartingDate();
updateTimer();
if (_typeof(params.target) === 'object') {
targetValues = setTarget(params.target);
} else if (countdown) {
params.target = {
seconds: 0
};
targetValues = setTarget(params.target);
} else {
targetValues = null;
}
timerConfig = {
precision: precision,
callback: customCallback,
countdown: _typeof(params) === 'object' && params.countdown === true,
target: targetValues,
startValues: startValues
};
currentParams = params;
}
function checkPrecision(precision) {
precision = typeof precision === 'string' ? precision : SECONDS;
if (!isValidInputValue(precision)) {
throw new Error("Error in precision parameter: ".concat(precision, " is not a valid value"));
}
return precision;
}
function isValidInputValue(value) {
return VALID_INPUT_VALUES.indexOf(value) >= 0;
}
function configInputValues(inputValues) {
var secondTenths, seconds, minutes, hours, days, values;
if (_typeof(inputValues) === 'object') {
if (inputValues instanceof Array) {
if (inputValues.length !== 5) {
throw new Error('Array size not valid');
}
values = inputValues;
} else {
for (var value in inputValues) {
if (VALID_INPUT_VALUES.indexOf(value) < 0) {
throw new Error("Error in startValues or target parameter: ".concat(value, " is not a valid input value"));
}
}
values = [inputValues.secondTenths || 0, inputValues.seconds || 0, inputValues.minutes || 0, inputValues.hours || 0, inputValues.days || 0];
}
}
secondTenths = values[SECOND_TENTHS_POSITION];
seconds = values[SECONDS_POSITION] + calculateIntegerUnitQuotient(secondTenths, SECOND_TENTHS_PER_SECOND);
minutes = values[MINUTES_POSITION] + calculateIntegerUnitQuotient(seconds, SECONDS_PER_MINUTE);
hours = values[HOURS_POSITION] + calculateIntegerUnitQuotient(minutes, MINUTES_PER_HOUR);
days = values[DAYS_POSITION] + calculateIntegerUnitQuotient(hours, HOURS_PER_DAY);
values[SECOND_TENTHS_POSITION] = secondTenths % SECOND_TENTHS_PER_SECOND;
values[SECONDS_POSITION] = seconds % SECONDS_PER_MINUTE;
values[MINUTES_POSITION] = minutes % MINUTES_PER_HOUR;
values[HOURS_POSITION] = hours % HOURS_PER_DAY;
values[DAYS_POSITION] = days;
return values;
}
function calculateIntegerUnitQuotient(unit, divisor) {
var quotient = unit / divisor;
return quotient < 0 ? Math.ceil(quotient) : Math.floor(quotient);
}
function setTarget(inputTarget) {
if (!inputTarget) {
return;
}
targetValues = configInputValues(inputTarget);
var targetCounter = calculateTotalCounterFromValues(targetValues);
targetDate = startingDate + targetCounter.secondTenths * unitsInMilliseconds[SECOND_TENTHS] * timerTypeFactor;
return targetValues;
}
function setStartValues(inputStartValues) {
startValues = configInputValues(inputStartValues);
counters.secondTenths = startValues[SECOND_TENTHS_POSITION];
counters.seconds = startValues[SECONDS_POSITION];
counters.minutes = startValues[MINUTES_POSITION];
counters.hours = startValues[HOURS_POSITION];
counters.days = startValues[DAYS_POSITION];
totalCounters = calculateTotalCounterFromValues(startValues, totalCounters);
}
function calculateTotalCounterFromValues(values, outputCounter) {
var total = outputCounter || {};
total.days = values[DAYS_POSITION];
total.hours = total.days * HOURS_PER_DAY + values[HOURS_POSITION];
total.minutes = total.hours * MINUTES_PER_HOUR + values[MINUTES_POSITION];
total.seconds = total.minutes * SECONDS_PER_MINUTE + values[SECONDS_POSITION];
total.secondTenths = total.seconds * SECOND_TENTHS_PER_SECOND + values[[SECOND_TENTHS_POSITION]];
return total;
}
/*
* PUBLIC functions
*/
/**
* [stop stops the timer and resets the counters. Dispatch stopped event]
*/
function stop() {
stopTimerAndResetCounters();
dispatchEvent('stopped', eventData);
}
/**
* [stop stops and starts the timer. Dispatch stopped event]
*/
function reset() {
stopTimerAndResetCounters();
setParamsAndStartTimer(currentParams);
dispatchEvent('reset', eventData);
}
/**
* [start starts the timer configured by the params object. Dispatch started event]
* @param {object} params [Configuration parameters]
*/
function start() {
var params = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
if (isRunning()) {
return;
}
setParamsAndStartTimer(params);
dispatchEvent('started', eventData);
}
/**
* [pause stops the timer without resetting the counters. The timer it can be restarted with start function.
* Dispatch paused event]
* @return {type} [description]
*/
function pause() {
stopTimer();
paused = true;
dispatchEvent('paused', eventData);
}
/**
* [addEventListener Adds event listener to the timer]
* @param {string} eventType [event to listen]
* @param {function} listener [the event listener function]
*/
function addEventListener(eventType, listener) {
if (hasDOM()) {
eventEmitter.addEventListener(eventType, listener);
} else if (hasEventEmitter()) {
eventEmitter.on(eventType, listener);
}
}
/**
* [removeEventListener Removes event listener to the timer]
* @param {string} eventType [event to remove listener]
* @param {function} listener [listener to remove]
*/
function removeEventListener(eventType, listener) {
if (hasDOM()) {
eventEmitter.removeEventListener(eventType, listener);
} else if (hasEventEmitter()) {
eventEmitter.removeListener(eventType, listener);
}
}
/**
* [dispatchEvent dispatches an event]
* @param {string} eventType [event to dispatch]
* @param data
*/
function dispatchEvent(eventType, data) {
if (hasDOM()) {
eventEmitter.dispatchEvent(new CustomEvent(eventType, data));
} else if (hasEventEmitter()) {
eventEmitter.emit(eventType, data);
}
}
/**
* [isRunning return true if the timer is running]
* @return {Boolean}
*/
function isRunning() {
return running;
}
/**
* [isPaused returns true if the timer is paused]
* @return {Boolean}
*/
function isPaused() {
return paused;
}
/**
* [getTimeValues returns the counter with the current timer values]
* @return {TimeCounter}
*/
function getTimeValues() {
return counters;
}
/**
* [getTotalTimeValues returns the counter with the current timer total values]
* @return {TimeCounter}
*/
function getTotalTimeValues() {
return totalCounters;
}
/**
* [getConfig returns the configuration parameters]
* @return {type}
*/
function getConfig() {
return timerConfig;
}
/**
* Public API
* Definition of Timer instance public functions
*/
if (typeof this !== 'undefined') {
this.start = start;
this.pause = pause;
this.stop = stop;
this.reset = reset;
this.isRunning = isRunning;
this.isPaused = isPaused;
this.getTimeValues = getTimeValues;
this.getTotalTimeValues = getTotalTimeValues;
this.getConfig = getConfig;
this.addEventListener = addEventListener;
this.on = addEventListener;
this.removeEventListener = removeEventListener;
this.off = removeEventListener;
}
}
exports.Timer = Timer;
exports.default = Timer;
Object.defineProperty(exports, '__esModule', { value: true });
}));