Worker
interface
interface Worker extends EventTargetThe Worker interface represents a background task that can be created via the
new Worker() constructor. Workers run in a separate thread, allowing for parallel execution
without blocking the main thread.
Workers can be used to:
- Perform CPU-intensive calculations
- Process large datasets
- Handle tasks in parallel with the main execution thread
- Run code in isolation with its own event loop
Example
// Creating a basic worker (main.ts)
const worker = new Worker(new URL("./worker.ts", import.meta.url).href, {
type: "module"
});
// Send data to the worker
worker.postMessage({ command: "start", data: [1, 2, 3, 4] });
// Receive messages from the worker
worker.onmessage = (e) => {
console.log("Result from worker:", e.data);
worker.terminate(); // Stop the worker when done
};
// Handle worker errors
worker.onerror = (e) => {
console.error("Worker error:", e.message);
};
Example
// Worker file (worker.ts)
// Worker context: self refers to the worker's global scope
self.onmessage = (e) => {
if (e.data.command === "start") {
// Perform calculation with the data
const result = e.data.data.reduce((sum, num) => sum + num, 0);
// Send result back to main thread
self.postMessage(result);
}
};
variable
var Worker: { … }The Worker constructor creates a new Worker object that executes code in a separate thread.
Workers can import ES modules when created with the type: "module" option.
Constructors
constructor
new Worker(specifier: string | URL, options?: WorkerOptions): WorkerCreates a new Worker object.
specifier: string | URLURL or file path for the worker's script. When using a relative path, use
new URL("./worker.ts", import.meta.url)to ensure the path is correctly resolved relative to the current module.options?: WorkerOptionsWorker options including type and name
Example: Module worker with URL resolution
// Create a worker that can use ES modules
const worker = new Worker(
new URL("./workers/heavy_computation.ts", import.meta.url).href,
{ type: "module", name: "computation-worker" }
);
Example: Worker communication pattern
// Main thread
const worker = new Worker(new URL("./worker.ts", import.meta.url).href, { type: "module" });
// Set up communication
worker.postMessage({ action: "start", data: [1, 2, 3, 4, 5] });
worker.onmessage = (e) => {
console.log("Worker result:", e.data);
if (e.data.status === "complete") {
worker.terminate();
}
};
// Worker file (worker.ts)
// self.onmessage = (e) => {
// if (e.data.action === "start") {
// const result = e.data.data.reduce((a, b) => a + b, 0);
// self.postMessage({ status: "complete", result });
// }
// };
Properties
onerror
onerror: ((this: Worker, e: ErrorEvent) => any) | nullEvent handler for error events. Fired when an error occurs in the worker's execution context.
onmessage
onmessage: ((this: Worker, e: MessageEvent) => any) | nullEvent handler for message events. Fired when the worker sends data back to the main thread.
onmessageerror
onmessageerror: ((this: Worker, e: MessageEvent) => any) | nullEvent handler for message error events. Fired when a message cannot be deserialized.
prototype
readonly prototype: WorkerMethods
postMessage
postMessage(message: any, transfer: Transferable[]): voidSends a message to the worker, transferring ownership of the specified transferable objects.
Example
// Create a buffer to transfer (not copy) to the worker
const buffer = new ArrayBuffer(1024);
worker.postMessage({ data: buffer }, [buffer]);
// After transfer, buffer is no longer usable in the main thread
postMessage(message: any, options?: StructuredSerializeOptions): voidSends a message to the worker.
Example
// Send a simple message with data
worker.postMessage({
command: "process",
data: [1, 2, 3, 4],
settings: { optimize: true }
});
addEventListener
addEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): voidAdds an event listener to the worker.
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): voidAdds an event listener for events whose type attribute value is type.
removeEventListener
removeEventListener<K extends keyof WorkerEventMap>(type: K, listener: (this: Worker, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): voidRemoves an event listener from the worker.
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): voidRemoves an event listener from the worker.
terminate
terminate(): voidImmediately terminates the worker. This does not offer the worker an opportunity to finish its operations; it is stopped at once.
Example
// Create a worker
const worker = new Worker(new URL("./worker.ts", import.meta.url).href, {
type: "module"
});
// Some time later, when you're done with the worker
worker.terminate();
// The worker is now terminated and its resources are freed