Full answer
JavaScript on the main thread handles rendering, input and your code. A 300 ms loop makes the page unresponsive for 300 ms. Typical causes: parsing large files, sorting or filtering tens of thousands of rows, image processing, and cryptography.
How to use a worker in Angular:
ng generate web-worker gradecreatesgrade.worker.tsand atsconfig.worker.json, and addswebWorkerTsConfigto the build options. The worker file starts with/// <reference lib="webworker" />.- Create it with
new Worker(new URL('./grade.worker', import.meta.url), { type: 'module' }). The builder recognises this pattern and bundles the worker separately. - Send data with
worker.postMessage(data), and receive results inworker.onmessage. Data is copied with the structured clone algorithm, so functions, DOM nodes and class instances with methods cannot be sent. LargeArrayBuffers can be transferred (postMessage(buf, [buf])) to avoid copying. - Terminate with
worker.terminate()when no longer needed, typically inDestroyRef.onDestroy.
Good structure:
- Put the algorithm in a plain function (
rankStudents) in its own file. The worker imports it, and unit tests call it directly without any worker. - Type the messages: a
Requestand aResponsetype shared by both sides. Include anidto match responses to requests when several run at once. - Wrap the worker in a service that exposes a Promise or a signal, and handles errors (
onerror,onmessageerror). - Check
typeof Worker !== 'undefined'. During server rendering there is noWorker, so fall back to running the function inline.
Limits: workers have no DOM and no access to Angular services. Messages have a cost, so a worker does not help for tiny tasks. A pool, or a library such as Comlink, helps with many calls. For work that must stay on the main thread, split it into chunks with scheduler.yield() or setTimeout.
// file: rank-students.ts
export interface Student {
name: string;
marks: number;
}
export interface RankRequest {
id: number;
students: Student[];
}
export interface RankResponse {
id: number;
ranked: Array<Student & { rank: number }>;
}
export function rankStudents(students: Student[]): Array<Student & { rank: number }> {
const sorted = [...students].sort((a, b) => b.marks - a.marks || a.name.localeCompare(b.name));
return sorted.map((s, i) => ({ ...s, rank: i + 1 }));
}
// file: rank.worker.ts
/// <reference lib="webworker" />
import { rankStudents, RankRequest, RankResponse } from './rank-students';
addEventListener('message', ({ data }: MessageEvent<RankRequest>) => {
const response: RankResponse = { id: data.id, ranked: rankStudents(data.students) };
postMessage(response);
});
// file: rank.service.ts
import { DestroyRef, Injectable, PLATFORM_ID, inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
import { RankRequest, RankResponse, Student, rankStudents } from './rank-students';
@Injectable({ providedIn: 'root' })
export class RankService {
private nextId = 1;
private readonly pending = new Map<number, (r: RankResponse['ranked']) => void>();
private worker?: Worker;
constructor() {
if (isPlatformBrowser(inject(PLATFORM_ID)) && typeof Worker !== 'undefined') {
this.worker = new Worker(new URL('./rank.worker', import.meta.url), { type: 'module' });
this.worker.onmessage = ({ data }: MessageEvent<RankResponse>) => {
this.pending.get(data.id)?.(data.ranked);
this.pending.delete(data.id);
};
inject(DestroyRef).onDestroy(() => this.worker?.terminate());
}
}
rank(students: Student[]): Promise<RankResponse['ranked']> {
if (!this.worker) {
return Promise.resolve(rankStudents(students)); // server or old browser
}
const id = this.nextId++;
const request: RankRequest = { id, students };
return new Promise((resolve) => {
this.pending.set(id, resolve);
this.worker!.postMessage(request);
});
}
}
// file: demo.ts
import { rankStudents } from './rank-students.ts';
const result = rankStudents([
{ name: 'Asha', marks: 82 },
{ name: 'Ravi', marks: 91 },
{ name: 'Meena', marks: 82 },
]);
console.log(result);Angular 20.3. The pure function was run in Node twice with identical output. The service and worker files are type-checked (the worker with `lib: webworker`). The worker was also bundled by `ng build` as a separate chunk, and a Karma spec in headless Chrome ranked students through the real worker. `ng generate web-worker` sets up `tsconfig.worker.json` and the build option.
Key points
- Workers run on another thread, so the UI stays responsive.
- `new Worker(new URL('./x.worker', import.meta.url), { type: 'module' })` is bundled by the CLI.
- Messages are copied. Use typed messages, ids, and transfer large buffers.
- Keep the algorithm pure for testing. Fall back when `Worker` is missing (SSR).
Common mistakes
- Trying to send functions or class instances and getting a clone error.
- Not terminating workers, which leaks threads.
- Using a worker for a task shorter than the message overhead.
Follow-ups
- How would you handle cancellation of a long-running job?
- How would you run several jobs in a pool?
- What can a worker not access?
Tips
- Start with a measured problem (a long task in the profiler), not with "use workers".
- Mention structured clone limits and transferables.
- Describe the SSR fallback.
Evaluation rubric
- Knows the bundling pattern and the message model.
- Designs a typed, testable, SSR-safe wrapper.
- Understands limits and costs.