parent
bb9c953d92
commit
3fe3691e74
@ -4,6 +4,7 @@ import humanizeDuration from "pretty-ms";
|
||||
|
||||
/**
|
||||
* Show time passed from date in human-friendly format
|
||||
* Updates every 5 seconds
|
||||
*
|
||||
* Usage example:
|
||||
* ```ts
|
||||
@ -16,17 +17,36 @@ export class RelativeDuration extends LitElement {
|
||||
@property({ type: String })
|
||||
value?: string; // `new Date` compatible date format
|
||||
|
||||
@state()
|
||||
private now = Date.now();
|
||||
|
||||
// For long polling:
|
||||
private timerId?: number;
|
||||
|
||||
static humanize(duration: number) {
|
||||
return humanizeDuration(duration, {
|
||||
secondsDecimalDigits: 0,
|
||||
});
|
||||
}
|
||||
|
||||
connectedCallback(): void {
|
||||
super.connectedCallback();
|
||||
|
||||
this.timerId = window.setInterval(() => this.updateValue(), 1000 * 5);
|
||||
}
|
||||
|
||||
disconnectedCallback(): void {
|
||||
window.clearInterval(this.timerId);
|
||||
super.disconnectedCallback();
|
||||
}
|
||||
|
||||
render() {
|
||||
if (!this.value) return "";
|
||||
|
||||
return RelativeDuration.humanize(
|
||||
Date.now() - new Date(this.value).valueOf()
|
||||
);
|
||||
return RelativeDuration.humanize(this.now - new Date(this.value).valueOf());
|
||||
}
|
||||
|
||||
private updateValue() {
|
||||
this.now = Date.now();
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user