aboutsummaryrefslogtreecommitdiff
path: root/demo/src/task-scheduler.ts
diff options
context:
space:
mode:
authorgfeun2020-03-19 18:35:35 +0100
committergfeun2020-03-20 18:03:29 +0100
commitc675c2a51c3a66f416cd2fd2ada1eccec45db2c9 (patch)
treefe7620d06da77edbabb0f2ca31e8c3db4b9d17ab /demo/src/task-scheduler.ts
parenttest: use tsconfig.spec.json when running jest (diff)
downloadavr8js-c675c2a51c3a66f416cd2fd2ada1eccec45db2c9.tar.gz
avr8js-c675c2a51c3a66f416cd2fd2ada1eccec45db2c9.tar.bz2
avr8js-c675c2a51c3a66f416cd2fd2ada1eccec45db2c9.zip
perf(demo): improve main cpu loop performance
Diffstat (limited to '')
-rw-r--r--demo/src/task-scheduler.ts39
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();
+ }
+ }
+ };
+}