diff options
| author | Uri Shaked | 2020-03-20 19:09:28 +0200 |
|---|---|---|
| committer | GitHub | 2020-03-20 19:09:28 +0200 |
| commit | 3c8b35275fa70544ec8529ca3154a75b55e8c8a5 (patch) | |
| tree | fe7620d06da77edbabb0f2ca31e8c3db4b9d17ab /demo/src/task-scheduler.ts | |
| parent | test: use tsconfig.spec.json when running jest (diff) | |
| parent | perf(demo): improve main cpu loop performance (diff) | |
| download | avr8js-3c8b35275fa70544ec8529ca3154a75b55e8c8a5.tar.gz avr8js-3c8b35275fa70544ec8529ca3154a75b55e8c8a5.tar.bz2 avr8js-3c8b35275fa70544ec8529ca3154a75b55e8c8a5.zip | |
Merge pull request #19 from gfeun/main-execute-loop-optimization
Improve main cpu loop performance
Diffstat (limited to '')
| -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(); + } + } + }; +} |
