interface Worker
The 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
Examples #
// 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);
};
// 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);
}
};
Properties #
#onerror: (this: Worker,e: ErrorEvent,) => any | null
Event handler for error events. Fired when an error occurs in the worker's execution context.
#onmessage: (this: Worker,e: MessageEvent,) => any | null
Event handler for message events. Fired when the worker sends data back to the main thread.
#onmessageerror: (this: Worker,e: MessageEvent,) => any | null
Event handler for message error events. Fired when a message cannot be deserialized.
Methods #
#postMessage(message: any,transfer: Transferable[],): void
Sends a message to the worker, transferring ownership of the specified transferable objects.
#postMessage(message: any,options?: StructuredSerializeOptions,): void
Sends a message to the worker.
#addEventListener<K extends keyof WorkerEventMap>(type: K,listener: (this: Worker,ev: WorkerEventMap[K],) => any,options?: boolean | AddEventListenerOptions,): void
Adds an event listener to the worker.
#addEventListener(type: string,listener: EventListenerOrEventListenerObject,options?: boolean | AddEventListenerOptions,): void
Adds an event listener for events whose type attribute value is type.
#removeEventListener<K extends keyof WorkerEventMap>(type: K,listener: (this: Worker,ev: WorkerEventMap[K],) => any,options?: boolean | EventListenerOptions,): void
Removes an event listener from the worker.
#removeEventListener(): void
Removes an event listener from the worker.