Last active
January 2, 2025 02:42
-
-
Save hunghg255/347bc211d315ee68cdb598c8c0f6cb5b to your computer and use it in GitHub Desktop.
Run code on worker
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
1 vài thư viện: | |
https://github.com/developit/workerize | |
https://github.com/developit/greenlet | |
https://github.com/Leka74/easythread | |
https://github.com/GoogleChromeLabs/comlink |
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
export function accurateSetInterval(fn, time) { | |
const stringFunction = `() => { | |
setInterval(() => { | |
postMessage({}); | |
}, ${time}); | |
}`; | |
const worker = new Worker(URL.createObjectURL(new Blob([`(${stringFunction})()`], {type: 'application/javascript'}))); | |
worker.onmessage = () => fn(); | |
return () => { | |
worker.terminate(); | |
} | |
} |
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
export function inlineWorker(fn) { | |
const stringFunction = `() => { | |
postMessage({}); | |
}`; | |
const worker = new Worker(URL.createObjectURL(new Blob([`(${stringFunction})()`], {type: 'application/javascript'}))); | |
worker.onmessage = () => fn(); | |
return () => { | |
worker.terminate(); | |
} | |
} | |
function inlineWorker(source) { | |
let blob = new Blob ([source], { | |
type: "text/javascript", | |
}); | |
let url = URL. createObjectURL(blob); | |
let worker = new Worker(url); | |
URL.revokeObjectURL(url) ; | |
return worker; | |
} | |
const worker = inlineWorker(` | |
console. log ("hello from worker!") | |
`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment