diff options
| author | Uri Shaked | 2021-02-14 16:20:37 +0200 |
|---|---|---|
| committer | Uri Shaked | 2021-02-14 16:23:49 +0200 |
| commit | 0ce082e4d621bef5083f05cebaeba8b06e4eac2b (patch) | |
| tree | f2c5091ec05d352b90b104b129893a33b16a4a25 /demo/src/task-scheduler.ts | |
| parent | 0.14.10 (diff) | |
| download | avr8js-0ce082e4d621bef5083f05cebaeba8b06e4eac2b.tar.gz avr8js-0ce082e4d621bef5083f05cebaeba8b06e4eac2b.tar.bz2 avr8js-0ce082e4d621bef5083f05cebaeba8b06e4eac2b.zip | |
feat(demo): web worker support
rewrite TaskScheduler to use `MessageChannel` instead of `window.postMessage`, to make the code portable into a Web Worker.
Diffstat (limited to '')
| -rw-r--r-- | demo/src/task-scheduler.ts | 23 |
1 files changed, 9 insertions, 14 deletions
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<IMicroTaskCallback> = []; 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(); } }; } |
