diff --git a/packages/reactivity-core/TaskQueue.ts b/packages/reactivity-core/TaskQueue.ts index e20714d..1377309 100644 --- a/packages/reactivity-core/TaskQueue.ts +++ b/packages/reactivity-core/TaskQueue.ts @@ -14,10 +14,7 @@ export class TaskQueue { private queue: Task[] = []; private channel = new MessageChannel(); - constructor() { - // https://stackoverflow.com/a/61574326 - this.channel.port2.onmessage = () => this.runIteration(); - } + constructor() {} /** * Enqueues a function to be executed in the next task queue iteration. @@ -53,11 +50,18 @@ export class TaskQueue { }; } + private messageHandler = () => this.runIteration(); private scheduleIteration() { + // register and unregister for every iteration otherwise node will not terminate + // https://stackoverflow.com/a/61574326 + this.channel.port2.addEventListener("message", this.messageHandler); + this.channel.port1.postMessage(""); // queue macro task } private runIteration() { + this.channel.port2.removeEventListener("message", this.messageHandler); + // Swap arrays so that NEW tasks are not queued into the same array; // they will be handled in the next iteration. const tasks = this.queue;