Skip to content
This repository has been archived by the owner on Oct 25, 2022. It is now read-only.

Commit

Permalink
feat: Tail-controlled main loop
Browse files Browse the repository at this point in the history
  • Loading branch information
oliversalzburg committed Apr 27, 2022
1 parent c9f10a9 commit 0722543
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions packages/userscript/source/Engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,9 +86,19 @@ export class Engine {
return;
}

// TODO: `_iterate` is async, but it isn't awaited.
// Instead of using an interval, this should use a tail-controlled timeout.
this._intervalMainLoop = setInterval(this._iterate.bind(this), this._host.options.interval);
const loop = () => {
const entry = Date.now();
this._iterate()
.then(() => {
const exit = Date.now();
const timeTaken = exit - entry;
setTimeout(loop, Math.max(10, this._host.options.interval - timeTaken));
})
.catch(error => {
this._host.warning(error as string);
});
};
this._intervalMainLoop = setTimeout(loop, this._host.options.interval);

if (msg) {
this._host.imessage("status.ks.enable");
Expand All @@ -104,7 +114,7 @@ export class Engine {
return;
}

clearInterval(this._intervalMainLoop);
clearTimeout(this._intervalMainLoop);
this._intervalMainLoop = undefined;

if (msg) {
Expand Down

0 comments on commit 0722543

Please sign in to comment.