Skip to content

Commit

Permalink
Check day every hour
Browse files Browse the repository at this point in the history
  • Loading branch information
piitaya committed May 12, 2023
1 parent 3bfbb6f commit dfe79fd
Showing 1 changed file with 29 additions and 3 deletions.
32 changes: 29 additions & 3 deletions src/components/ha-absolute-time.ts
Expand Up @@ -4,6 +4,9 @@ import { customElement, property } from "lit/decorators";
import { absoluteTime } from "../common/datetime/absolute_time";
import type { HomeAssistant } from "../types";

const ONE_HOUR = 60 * 60 * 1000;
const SAFE_MARGIN = 5 * 1000;

@customElement("ha-absolute-time")
class HaAbsoluteTime extends ReactiveElement {
@property({ attribute: false }) public hass!: HomeAssistant;
Expand All @@ -12,17 +15,20 @@ class HaAbsoluteTime extends ReactiveElement {

private _lastUpdate?: Date;

private _timeout?: number;

private _interval?: number;

public disconnectedCallback(): void {
super.disconnectedCallback();
this._clearTimeout();
this._clearInterval();
}

public connectedCallback(): void {
super.connectedCallback();
if (this.datetime) {
this._startInterval();
this._startTimeout();
}
}

Expand All @@ -40,6 +46,26 @@ class HaAbsoluteTime extends ReactiveElement {
this._updateAbsolute();
}

private _clearTimeout(): void {
if (this._interval) {
window.clearTimeout(this._timeout);
this._timeout = undefined;
}
}

private _startTimeout(): void {
this._clearInterval();
this._clearTimeout();

const msToNextHour =
ONE_HOUR - (new Date().getTime() % ONE_HOUR) + SAFE_MARGIN;

this._timeout = window.setTimeout(() => {
this._updateAbsolute();
this._startInterval();
}, msToNextHour);
}

private _clearInterval(): void {
if (this._interval) {
window.clearInterval(this._interval);
Expand All @@ -50,13 +76,13 @@ class HaAbsoluteTime extends ReactiveElement {
private _startInterval(): void {
this._clearInterval();

// update every 60 seconds
// update every hour
this._interval = window.setInterval(() => {
if (this._lastUpdate && isSameDay(this._lastUpdate, new Date())) {
return;
}
this._updateAbsolute();
}, 60000);
}, ONE_HOUR);
}

private _updateAbsolute(): void {
Expand Down

0 comments on commit dfe79fd

Please sign in to comment.