Skip to content

Instantly share code, notes, and snippets.

@hunghg255
Last active January 2, 2025 02:42
Show Gist options
  • Save hunghg255/347bc211d315ee68cdb598c8c0f6cb5b to your computer and use it in GitHub Desktop.
Save hunghg255/347bc211d315ee68cdb598c8c0f6cb5b to your computer and use it in GitHub Desktop.
Run code on worker
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
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();
}
}
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