Show timer, set time on create
This commit is contained in:
65
static/ui-components.js
Normal file
65
static/ui-components.js
Normal file
@ -0,0 +1,65 @@
|
||||
class LocalDate extends HTMLElement {
|
||||
connectedCallback() {
|
||||
let utcDate = new Date(this.innerText);
|
||||
this.innerText = utcDate.toLocaleString();
|
||||
}
|
||||
}
|
||||
customElements.define("local-date", LocalDate);
|
||||
|
||||
class TimerCountdown extends HTMLElement {
|
||||
startTime;
|
||||
endTime;
|
||||
refreshInterval = null;
|
||||
|
||||
refreshCountdown() {
|
||||
let diff = Math.floor((this.endTime - this.startTime) / 1000);
|
||||
if (diff <= 0) {
|
||||
this.innerText = "Finished";
|
||||
return;
|
||||
}
|
||||
|
||||
let days = Math.floor(diff / (24 * 60 * 60));
|
||||
diff -= days * 24 * 60 * 60;
|
||||
let hours = Math.floor(diff / (60 * 60));
|
||||
diff -= hours * 60 * 60;
|
||||
let minutes = Math.floor(diff / 60);
|
||||
diff -= minutes * 60;
|
||||
let seconds = diff;
|
||||
|
||||
let newText = "";
|
||||
if (days > 0) {
|
||||
newText += `${days} days, `;
|
||||
}
|
||||
newText += `${hours.toFixed(0).padStart(2, "0")}:`
|
||||
+ `${minutes.toFixed(0).padStart(2, "0")}:`
|
||||
+ `${seconds.toFixed(0).padStart(2, "0")}`;
|
||||
|
||||
this.innerText = newText;
|
||||
}
|
||||
|
||||
refreshCountdownNow() {
|
||||
this.startTime = (new Date()).getTime();
|
||||
this.refreshCountdown();
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
this.endTime = (new Date(this.getAttribute("end"))).getTime();
|
||||
if (this.hasAttribute("start")) {
|
||||
this.startTime = (new Date(this.getAttribute("start"))).getTime();
|
||||
this.refreshCountdown();
|
||||
}
|
||||
else {
|
||||
this.startTime = (new Date()).getTime();
|
||||
this.refreshCountdown();
|
||||
this.refreshInterval = setInterval(this.refreshCountdownNow.bind(this), 1000);
|
||||
}
|
||||
}
|
||||
|
||||
disconnectedCallback() {
|
||||
if (this.refreshInterval !== null) {
|
||||
clearInterval(this.refreshInterval);
|
||||
}
|
||||
}
|
||||
}
|
||||
customElements.define("timer-countdown", TimerCountdown);
|
||||
|
Reference in New Issue
Block a user