/ concept-collection / turing-surface
Sign in
concept-collection / turing-surface
40 lines · 1.3 KBBlameHistoryRaw
1/**
2 * Drawing a seed field's Fourier modes, off the main thread.
3 *
4 * The draw is `tools/randnfun3.m` in numbl's interpreter, and its cost goes as
5 * the inverse cube of the wavelength: milliseconds at the default lambda, but
6 * ~13 s at lambda 0.01. Synchronous JS that long does not merely feel slow —
7 * it blocks the event loop outright, so the page stops painting and the
8 * browser offers to kill it. Nothing about the draw needs the main thread
9 * (it touches no GPU and no DOM), so it runs here and the result is
10 * transferred back.
11 */
12import { drawModes, type BoundingBox } from './randnfun3.ts';
14export interface DrawRequest {
15 id: number;
16 lambda: number;
17 box: BoundingBox;
18 seed: number;
19 npts: number;
22export type DrawReply =
23 | { id: number; table: Float32Array; error?: undefined }
24 | { id: number; table?: undefined; error: string };
26self.onmessage = (e: MessageEvent<DrawRequest>): void => {
27 const { id, lambda, box, seed, npts } = e.data;
28 let reply: DrawReply;
29 let transfer: Transferable[] = [];
30 try {
31 const table = drawModes(lambda, box, seed, npts);
32 reply = { id, table };
33 transfer = [table.buffer];
34 } catch (err) {
35 reply = { id, error: err instanceof Error ? err.message : String(err) };
36 }
37 (self as unknown as {
38 postMessage: (m: DrawReply, t: Transferable[]) => void;
39 }).postMessage(reply, transfer);
40};
moveopenescclose