Skip to content

Thread

Thread is a base class for running CPU-bound work on a background thread (a Web Worker). Extend it, override run() and onMessage(), then call start().

import { Thread } from "jops-core";

Learn more: Threads.

run(params: any): void

The work the thread performs. It runs inside the Web Worker, so it must be self-contained: it has no access to the outer scope, imports or the class instance (this). Send results back with self.postMessage(result).

Parameters

  • params: the value passed to start().
onMessage(event: MessageEvent): void

Runs on the main thread for every message the worker posts with self.postMessage(). The result is in event.data.

start(params?: any): void

Spawns the Web Worker, runs run(params) in it, and routes its messages to onMessage().

Parameters

  • params (optional): data passed to run(params) inside the worker. It is copied to the worker, so it must be serializable (plain objects, arrays, strings, numbers…).
terminate(): void

Stops the worker immediately and clears the internal reference. Safe to call when the worker has already finished (it only logs a warning when no worker was started). After terminate(), start() can spawn a new worker.

src/HashThread.js
import { Thread } from "jops-core";
export default class HashThread extends Thread {
run(params) {
// runs on a background thread: no access to the main thread or the instance
let hash = 0;
for (let i = 0; i < params.data.length; i++) hash ^= params.data.charCodeAt(i);
self.postMessage(hash);
}
onMessage(event) {
console.log("Hash result:", event.data);
}
}
const t = new HashThread();
t.start({ data: "hello world" });
// later:
t.terminate();