2020-01-20 04:40:23 +08:00
|
|
|
export default class SpacedUpdate {
|
|
|
|
constructor(updater, updateInterval = 1000) {
|
|
|
|
this.updater = updater;
|
|
|
|
this.lastUpdated = Date.now();
|
|
|
|
this.changed = false;
|
|
|
|
this.updateInterval = updateInterval;
|
|
|
|
}
|
|
|
|
|
|
|
|
scheduleUpdate() {
|
2020-02-02 05:29:32 +08:00
|
|
|
if (!this.changeForbidden) {console.trace();
|
2020-01-25 05:30:17 +08:00
|
|
|
this.changed = true;
|
|
|
|
setTimeout(() => this.triggerUpdate());
|
|
|
|
}
|
2020-01-20 04:40:23 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
async updateNowIfNecessary() {
|
|
|
|
if (this.changed) {
|
|
|
|
this.changed = false;
|
|
|
|
await this.updater();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
triggerUpdate() {
|
|
|
|
if (!this.changed) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Date.now() - this.lastUpdated > this.updateInterval) {
|
|
|
|
this.updater();
|
|
|
|
this.lastUpdated = Date.now();
|
|
|
|
this.changed = false;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
// update not triggered but changes are still pending so we need to schedule another check
|
|
|
|
this.scheduleUpdate();
|
|
|
|
}
|
|
|
|
}
|
2020-01-25 05:30:17 +08:00
|
|
|
|
|
|
|
allowUpdateWithoutChange(callback) {
|
|
|
|
this.changeForbidden = true;
|
|
|
|
|
|
|
|
try {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
finally {
|
|
|
|
this.changeForbidden = false;
|
|
|
|
}
|
|
|
|
}
|
2020-01-20 04:40:23 +08:00
|
|
|
}
|