Created
July 20, 2024 05:31
-
-
Save zazaulola/f7990ac56801d08e89e1bfc177c1333b to your computer and use it in GitHub Desktop.
Create local worker without HTTP request
This file contains 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
export function createWorker(callable) { | |
const code = `(${callable.toString()})()`; | |
const blob = new Blob([code], { type: 'text/javascript' }); | |
const url = URL.createObjectURL(blob); | |
const worker = new Worker(url); | |
URL.revokeObjectURL(url); | |
return worker; | |
} | |
export function executeWorker(callable, data) { | |
return new Promise((res) => { | |
const worker = createWorker(callable); | |
worker.postMessage(data); | |
worker.onmessage = ({ data }) => { | |
worker.terminate(); | |
res(data); | |
}; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment