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.
Methods to override
Section titled “Methods to override”run(params: any): voidThe 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 tostart().
onMessage()
Section titled “onMessage()”onMessage(event: MessageEvent): voidRuns on the main thread for every message the worker posts with self.postMessage(). The result is in event.data.
Instance methods
Section titled “Instance methods”start()
Section titled “start()”start(params?: any): voidSpawns the Web Worker, runs run(params) in it, and routes its messages to onMessage().
Parameters
params(optional): data passed torun(params)inside the worker. It is copied to the worker, so it must be serializable (plain objects, arrays, strings, numbers…).
terminate()
Section titled “terminate()”terminate(): voidStops 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.
Example
Section titled “Example”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();