JavaScript
Web Worker
Create a Web Worker to run time-consuming tasks.
By EZ4Code Team
workermultithreading
Code
function createWorker(fn) {
const blob = new Blob([`(${fn.toString()})()`], { type: "application/javascript" });
const worker = new Worker(URL.createObjectURL(blob));
return worker;
}
const worker = createWorker(() => {
self.onmessage = e => {
const result = e.data.reduce((s, n) => s + n, 0);
self.postMessage(result);
};
});
worker.postMessage([1, 2, 3, 4, 5]);
worker.onmessage = e => console.log(e.data);Explanation
Dynamically creates a Worker via Blob, without a separate worker file.
More JavaScript Snippets
Array Map Filter Reduce
Chain map, filter, reduce, find, some, and every on arrays.
Array Deduplication
Deduplicate an array using Set.
Deep Clone
Deep clone objects, supporting common data types.
Debounce Function
Wait a period of time after an event triggers before executing; reset the timer if triggered again during the wait.
Throttle Function
Limit a function to execute at most once within a time interval.
Promise.all Concurrency Control
A Promise executor with concurrency limit.