Created
October 17, 2018 23:48
-
-
Save pokatomnik/f438e2984a7c68e3c51ff08ca602fb4a to your computer and use it in GitHub Desktop.
Web worker async task
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* This is a simple example of web worker | |
* Background task is a class which creates a new thread. | |
* 'fn' is a heavy CPU utilization function | |
* 'start' method accepts only one argument (a message for web worker) | |
* Restrictions: | |
* - fn must be a pure function. It does not have an access to any outer scope vars. | |
* - fn must not be native function. | |
* - fn must not be bound to any 'this' | |
*/ | |
// Main class | |
class BackgroundTask { | |
constructor(fn) { | |
this.fn = fn; | |
this.blob = null; | |
this.worker = null; | |
} | |
start(message) { | |
this.blob = new Blob([ | |
`self.onmessage=${this.fn.toString()}` | |
], {type: 'application/javascript'}); | |
this.worker = new Worker(URL.createObjectURL(this.blob)); | |
this.worker.postMessage(message); | |
return new Promise((resolve) => { | |
this.worker.onmessage = ({data}) => { | |
resolve(data); | |
this.worker.terminate(); | |
}; | |
}) | |
} | |
} | |
// Heavy CPU Fibonacci example | |
new BackgroundTask(function fibonacci(msg) { | |
const fib = (n) => n < 1 ? 0 | |
: n <= 2 ? 1 | |
: fib(n - 1) + fib(n - 2); | |
this.postMessage(fib(+msg.data)); | |
}) | |
.start('50') | |
.then((data) => { | |
console.log(data); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment