Offload heavy computations to Web Workers for responsive Google Antigravity applications.
# Web Workers Patterns for Google Antigravity
Web Workers enable running JavaScript in background threads, keeping your UI responsive during heavy computations. This guide covers effective patterns for Web Workers in Google Antigravity projects.
## Basic Worker Setup
```typescript
// workers/computation.worker.ts
self.onmessage = async (event: MessageEvent) => {
const { type, payload } = event.data;
switch (type) {
case "PROCESS_DATA":
const result = await processLargeDataset(payload);
self.postMessage({ type: "RESULT", payload: result });
break;
case "CALCULATE":
const calculation = performHeavyCalculation(payload);
self.postMessage({ type: "CALCULATION_DONE", payload: calculation });
break;
}
};
function processLargeDataset(data: number[]): number[] {
return data.map((item) => {
let result = item;
for (let i = 0; i < 1000; i++) {
result = Math.sqrt(result * result + i);
}
return result;
});
}
function performHeavyCalculation(params: { iterations: number; seed: number }): number {
let value = params.seed;
for (let i = 0; i < params.iterations; i++) {
value = (value * 1103515245 + 12345) % 2147483648;
}
return value;
}
export {};
```
## Worker Manager Class
```typescript
// lib/worker-manager.ts
export class WorkerManager<TInput, TOutput> {
private worker: Worker | null = null;
private pending: Map<string, { resolve: (value: TOutput) => void; reject: (error: Error) => void }> = new Map();
constructor(private workerPath: string) {}
private getWorker(): Worker {
if (!this.worker) {
this.worker = new Worker(new URL(this.workerPath, import.meta.url));
this.worker.onmessage = (event) => {
const { id, result, error } = event.data;
const pending = this.pending.get(id);
if (pending) {
if (error) pending.reject(new Error(error));
else pending.resolve(result);
this.pending.delete(id);
}
};
this.worker.onerror = (error) => console.error("Worker error:", error);
}
return this.worker;
}
execute(type: string, payload: TInput): Promise<TOutput> {
return new Promise((resolve, reject) => {
const id = crypto.randomUUID();
this.pending.set(id, { resolve, reject });
this.getWorker().postMessage({ id, type, payload });
});
}
terminate(): void {
this.worker?.terminate();
this.worker = null;
this.pending.clear();
}
}
```
## React Hook for Workers
```typescript
// hooks/useWorker.ts
import { useRef, useCallback, useEffect, useState } from "react";
export function useWorker<TInput, TOutput>(workerPath: string) {
const workerRef = useRef<Worker | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
const [result, setResult] = useState<TOutput | null>(null);
useEffect(() => {
workerRef.current = new Worker(new URL(workerPath, import.meta.url));
workerRef.current.onmessage = (event) => { setResult(event.data.payload); setLoading(false); };
workerRef.current.onerror = (e) => { setError(new Error(e.message)); setLoading(false); };
return () => { workerRef.current?.terminate(); };
}, [workerPath]);
const execute = useCallback((type: string, payload: TInput) => {
setLoading(true);
setError(null);
workerRef.current?.postMessage({ type, payload });
}, []);
return { execute, result, loading, error };
}
```
## Worker Pool for Parallel Processing
```typescript
// lib/worker-pool.ts
export class WorkerPool<T> {
private workers: Worker[] = [];
private queue: Array<{ task: T; resolve: (result: unknown) => void }> = [];
private activeWorkers = 0;
constructor(private workerPath: string, private poolSize: number = navigator.hardwareConcurrency || 4) {
for (let i = 0; i < this.poolSize; i++) {
this.workers.push(new Worker(new URL(workerPath, import.meta.url)));
}
}
async executeAll(tasks: T[]): Promise<unknown[]> {
return Promise.all(tasks.map((task) => this.execute(task)));
}
private execute(task: T): Promise<unknown> {
return new Promise((resolve) => {
this.queue.push({ task, resolve });
this.processQueue();
});
}
private processQueue(): void {
if (this.queue.length === 0 || this.activeWorkers >= this.poolSize) return;
const { task, resolve } = this.queue.shift()!;
const worker = this.workers[this.activeWorkers];
this.activeWorkers++;
worker.onmessage = (event) => { this.activeWorkers--; resolve(event.data); this.processQueue(); };
worker.postMessage(task);
}
terminate(): void {
this.workers.forEach((w) => w.terminate());
this.workers = [];
this.queue = [];
}
}
```
## Best Practices
1. **Structured Cloning**: Be aware of data transfer costs; use Transferable objects for large buffers
2. **Error Handling**: Always handle worker errors to prevent silent failures
3. **Pool Management**: Use worker pools for parallel processing of multiple tasks
4. **Cleanup**: Terminate workers when components unmount to prevent memory leaks
5. **Fallbacks**: Provide main-thread fallbacks for environments without Worker supportThis web-workers prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their web-workers implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For web-workers projects, consider mentioning your framework version, coding style, and any specific libraries you're using.