deno.com

interface Worker

extends EventTarget

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,
) => any | null

Event handler for error events. Fired when an error occurs in the worker's execution context.

#onmessage: () => any | null

Event handler for message events. Fired when the worker sends data back to the main thread.

#onmessageerror: () => 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,
): void

Sends a message to the worker.

#addEventListener<K extends keyof WorkerEventMap>(
type: K,
listener: (
this: Worker,
) => any
,
options?: boolean | AddEventListenerOptions,
): void

Adds an event listener to the worker.

#addEventListener(
type: string,
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,
) => any
,
options?: boolean | EventListenerOptions,
): void

Removes an event listener from the worker.

#removeEventListener(
type: string,
options?: boolean | EventListenerOptions,
): void

Removes an event listener from the worker.

#terminate(): void

Immediately terminates the worker. This does not offer the worker an opportunity to finish its operations; it is stopped at once.

variable 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.

Properties #

#prototype: Worker
readonly