-
Notifications
You must be signed in to change notification settings - Fork 1
/
time-counter.html
117 lines (101 loc) · 3.09 KB
/
time-counter.html
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
<link rel="import" href="../polymer/polymer.html">
<dom-module id="time-counter">
<template>
<style>
:host {
display: inline-block;
}
</style>
<span>[[_formatDuration(duration, format)]]</span>
</template>
<script>
/**
* `time-counter`
* Web Component to display an incremental timer
*
* @customElement
* @polymer
* @demo demo/index.html
*/
Polymer({
is: 'time-counter',
properties: {
/**
* The current duration in milliseconds
*/
duration: {
type: Number,
notify: true,
value: 0
},
/**
* If set the duration will adapt as if it sarts counting from that date
*/
startDate: {
type: Number,
observer: '_handleStartDateChanged'
},
/**
* Output format for duration
*/
format: {
type: String,
value: 'hh:mm:ss'
}
},
_calcDuration: function (startDate, endDate) {
startDate = startDate || Date.now()
endDate = endDate || Date.now()
return endDate - startDate
},
_formatDuration: function (duration, format) {
var formattedDuration = ''
if (format) {
var durationInSeconds = Math.floor(duration / 1000)
var hours = Math.floor(durationInSeconds / 3600)
var minutes = Math.floor((durationInSeconds % 3600) / 60)
var seconds = durationInSeconds % 60
formattedDuration = format
.replace(/(h+)/g, function (match, group) {
return this._formatNumber(hours, group.length)
}.bind(this))
.replace(/(m+)/g, function (match, group) {
return this._formatNumber(minutes, group.length)
}.bind(this))
.replace(/(s+)/g, function (match, group) {
return this._formatNumber(seconds, group.length)
}.bind(this))
} else {
formattedDuration = this._formatNumber(hours) + ':' + this._formatNumber(minutes) + ':' + this._formatNumber(seconds)
}
return formattedDuration
},
_formatNumber: function (value, length) {
value = isNaN(value) ? '' : '' + value
length = length !== undefined ? length : 2
while (value.length < length) {
value = '0' + value
}
return value.substr(-length)
},
_handleStartDateChanged: function (startDate) {
if (startDate) {
this._updateDuration()
this._updateDurationDebounced()
} else if (this.isDebouncerActive('updateDuration')) {
this.cancelDebouncer('updateDuration')
this.duration = this.properties.duration.value
}
},
_updateDuration: function () {
this.duration = this._calcDuration(this.startDate)
},
_updateDurationDebounced: function () {
this.debounce('updateDuration', function () {
this._updateDuration()
this._updateDurationDebounced()
}, 500)
}
})
</script>
</dom-module>