Skip to content

Commit

Permalink
perf: Minimize the number of http fetches
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed May 8, 2024
1 parent 39d6bcd commit dd4c6fa
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/com.gabe565.nightscout.sdPlugin/js/Nightscout.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,38 @@ class Nightscout {
return;
}

let sleepMs = 60000;
try {
const response = await fetch(this.url, this.request);
const data = await response.json();
$SD.setImage(this.context, this.template.render(data, this.settings.unit));
const bucket = data?.buckets[0];
if (bucket) {
const lastDiff = bucket.toMills - bucket.fromMills;
const nextRead = data?.bgnow?.mills + lastDiff + 30000;
const now = Date.now();
if (nextRead - now > 0) {
sleepMs = nextRead - now;
}
}
} catch (err) {
console.error(err);
$SD.showAlert(this.context);
}
this.tickTimeout = setTimeout(() => this.tick(), sleepMs);
}

beginTick() {
if (!this.url) {
return;
}

this.tick();
this.stopTick();
this.tickInterval = setInterval(() => this.tick(), this.settings.updateInterval || 60000);
this.tick();
}

stopTick() {
clearInterval(this.tickInterval);
this.tickInterval = null;
clearTimeout(this.tickTimeout);
this.tickTimeout = null;
}
}

0 comments on commit dd4c6fa

Please sign in to comment.