diff options
Diffstat (limited to 'demo/src/task-scheduler.ts')
| -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(); } }; } |
