From 0ce082e4d621bef5083f05cebaeba8b06e4eac2b Mon Sep 17 00:00:00 2001 From: Uri Shaked Date: Sun, 14 Feb 2021 16:20:37 +0200 Subject: feat(demo): web worker support rewrite TaskScheduler to use `MessageChannel` instead of `window.postMessage`, to make the code portable into a Web Worker. --- demo/src/task-scheduler.ts | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) (limited to 'demo/src/task-scheduler.ts') diff --git a/demo/src/task-scheduler.ts b/demo/src/task-scheduler.ts index 5364d92..46413ef 100644 --- a/demo/src/task-scheduler.ts +++ b/demo/src/task-scheduler.ts @@ -1,39 +1,34 @@ -// Faster setTimeout(fn, 0) implementation using postMessage API -// Based on https://dbaron.org/log/20100309-faster-timeouts export type IMicroTaskCallback = () => void; export class MicroTaskScheduler { - readonly messageName = 'zero-timeout-message'; - + private readonly channel = new MessageChannel(); private executionQueue: Array = []; private stopped = true; start() { if (this.stopped) { this.stopped = false; - window.addEventListener('message', this.handleMessage, true); + this.channel.port2.onmessage = this.handleMessage; } } stop() { this.stopped = true; - window.removeEventListener('message', this.handleMessage, true); + this.executionQueue.splice(0, this.executionQueue.length); + this.channel.port2.onmessage = null; } postTask(fn: IMicroTaskCallback) { if (!this.stopped) { this.executionQueue.push(fn); - window.postMessage(this.messageName, '*'); + this.channel.port1.postMessage(null); } } - private handleMessage = (event: MessageEvent) => { - if (event.data === this.messageName) { - event.stopPropagation(); - const executeJob = this.executionQueue.shift(); - if (executeJob !== undefined) { - executeJob(); - } + private handleMessage = () => { + const executeJob = this.executionQueue.shift(); + if (executeJob !== undefined) { + executeJob(); } }; } -- cgit v1.2.3