Skip to content

Commit

Permalink
register and unregister for every iteration
Browse files Browse the repository at this point in the history
  • Loading branch information
anticultist committed Apr 12, 2024
1 parent 5cb2128 commit 5156f20
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions packages/reactivity-core/TaskQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit 5156f20

Please sign in to comment.