Files
Trilium/src/public/app/services/spaced_update.ts

74 lines
1.7 KiB
TypeScript
Raw Normal View History

type Callback = () => Promise<void> | void;
2020-01-19 21:40:23 +01:00
export default class SpacedUpdate {
private updater: Callback;
private lastUpdated: number;
private changed: boolean;
private updateInterval: number;
private changeForbidden?: boolean;
constructor(updater: Callback, updateInterval = 1000) {
2020-01-19 21:40:23 +01:00
this.updater = updater;
this.lastUpdated = Date.now();
this.changed = false;
this.updateInterval = updateInterval;
}
scheduleUpdate() {
if (!this.changeForbidden) {
2020-01-24 22:30:17 +01:00
this.changed = true;
setTimeout(() => this.triggerUpdate());
}
2020-01-19 21:40:23 +01:00
}
async updateNowIfNecessary() {
if (this.changed) {
this.changed = false; // optimistic...
try {
await this.updater();
}
catch (e) {
this.changed = true;
throw e;
}
2020-01-19 21:40:23 +01:00
}
}
isAllSavedAndTriggerUpdate() {
const allSaved = !this.changed;
this.updateNowIfNecessary();
return allSaved;
}
2020-01-19 21:40:23 +01:00
triggerUpdate() {
if (!this.changed) {
return;
}
if (Date.now() - this.lastUpdated > this.updateInterval) {
this.updater();
this.lastUpdated = Date.now();
this.changed = false;
}
else {
2023-06-30 11:18:34 +02:00
// update isn't triggered but changes are still pending, so we need to schedule another check
2020-01-19 21:40:23 +01:00
this.scheduleUpdate();
}
}
2020-01-24 22:30:17 +01:00
async allowUpdateWithoutChange(callback: Callback) {
2020-01-24 22:30:17 +01:00
this.changeForbidden = true;
try {
2020-02-08 21:23:42 +01:00
await callback();
2020-01-24 22:30:17 +01:00
}
finally {
this.changeForbidden = false;
}
}
2020-01-19 21:40:23 +01:00
}