diff options
| author | gfeun | 2020-03-19 18:35:35 +0100 |
|---|---|---|
| committer | gfeun | 2020-03-20 18:03:29 +0100 |
| commit | c675c2a51c3a66f416cd2fd2ada1eccec45db2c9 (patch) | |
| tree | fe7620d06da77edbabb0f2ca31e8c3db4b9d17ab /demo/src/task-scheduler.ts | |
| parent | test: use tsconfig.spec.json when running jest (diff) | |
| download | avr8js-c675c2a51c3a66f416cd2fd2ada1eccec45db2c9.tar.gz avr8js-c675c2a51c3a66f416cd2fd2ada1eccec45db2c9.tar.bz2 avr8js-c675c2a51c3a66f416cd2fd2ada1eccec45db2c9.zip | |
perf(demo): improve main cpu loop performance
Diffstat (limited to 'demo/src/task-scheduler.ts')
| -rw-r--r-- | demo/src/task-scheduler.ts | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/demo/src/task-scheduler.ts b/demo/src/task-scheduler.ts new file mode 100644 index 0000000..5364d92 --- /dev/null +++ b/demo/src/task-scheduler.ts @@ -0,0 +1,39 @@ +// 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 executionQueue: Array<IMicroTaskCallback> = []; + private stopped = true; + + start() { + if (this.stopped) { + this.stopped = false; + window.addEventListener('message', this.handleMessage, true); + } + } + + stop() { + this.stopped = true; + window.removeEventListener('message', this.handleMessage, true); + } + + postTask(fn: IMicroTaskCallback) { + if (!this.stopped) { + this.executionQueue.push(fn); + window.postMessage(this.messageName, '*'); + } + } + + private handleMessage = (event: MessageEvent) => { + if (event.data === this.messageName) { + event.stopPropagation(); + const executeJob = this.executionQueue.shift(); + if (executeJob !== undefined) { + executeJob(); + } + } + }; +} |
