HTML5 game publishing
Web Workers for Heavy Game Logic: Solvers, Generators and Pathfinding
Move long computations off the main thread: message ids for stale results, transferring typed arrays, budgets and progress, and fallbacks when a portal blocks workers.
JavaScript runs your game logic, your input handling and your rendering on one thread. If a puzzle solver, a pathfinding request or a level generator takes 300 milliseconds, the game freezes for 300 milliseconds: no animation, no response to taps, a visibly stuttering frame. A Web Worker runs code on a separate thread, so heavy work happens without blocking the game. This post shows how to use workers for solvers and pathfinding in a game, what to watch for and when a worker is not worth it.
What a worker is, and what it cannot do
A worker is a separate script that runs in its own thread. It has no access to the DOM, window or your canvas, and it shares no variables with the main thread. You talk to it by sending messages, and the data is copied (or transferred) between threads.
That makes workers a good fit for pure computation: given a board, return a solution; given a grid, return a path; given a seed, return a generated level. They are a poor fit for anything that needs to touch the screen.
A minimal worker setup
The worker file, solver.js:
self.onmessage = (e) => {
const { id, board } = e.data;
const solution = solve(board); // your heavy function
self.postMessage({ id, solution });
};
The main thread:
const worker = new Worker('solver.js');
const pending = new Map();
let nextId = 1;
worker.onmessage = (e) => {
const { id, solution } = e.data;
const resolve = pending.get(id);
if (resolve) { pending.delete(id); resolve(solution); }
};
function solveAsync(board) {
return new Promise(resolve => {
const id = nextId++;
pending.set(id, resolve);
worker.postMessage({ id, board });
});
}
Use an id on every request. Responses can return after the state they refer to has changed, and the id lets you recognize and discard stale ones. That same discipline appears in undo and hint systems for puzzle games, where a hint request can outlive the board it was made for.
Typed arrays and transfer
Messages are copied using structured cloning. That is fine for small objects. For big grids, send a typed array and transfer ownership, so nothing is copied:
const grid = new Uint8Array(W * H);
worker.postMessage({ id, grid }, [grid.buffer]); // grid is now unusable here
After a transfer, the sender's array is detached and empty. If you still need your copy, send a copy: grid.slice(). For read-heavy data shared by both sides, SharedArrayBuffer exists, but it requires cross-origin isolation headers that a game running inside an iframe on a portal typically cannot set. Do not depend on it.
Keep one worker, queue the work
Creating a worker costs tens of milliseconds and some memory. Create one at startup, or on first use, and reuse it. If a new request makes an old one pointless (the player moved again), you have two options:
- Ignore the stale answer by id when it arrives. Cheap and simple.
- Cancel it. Workers do not support cancellation of a running function, so the choices are to check a flag inside long loops (by sending a message that the worker reads between chunks) or to terminate the worker and start another. Only the second works for a function that never yields.
For long searches, structure the algorithm to do a chunk of work, check for a new message, and continue. In practice, await yielding with setTimeout(0) inside a worker lets queued messages arrive.
Report progress and give a budget
A generator that takes four seconds should not look frozen. Post progress messages and show a bar. Also give the worker a time budget: stop after, say, 1.5 seconds and return the best result so far, or a failure that your code handles by trying another seed. A hung worker is as bad as a hung main thread, so time-out on the main side too, and have a fallback. This is the same principle as a boot sequence that cannot hang.
Where it runs inside a portal
When your game is hosted on a portal, the worker script has to be loaded from the same origin as the page, as a separate file. An inline worker created from a Blob works around that in most browsers, but a portal's content security policy can block blob: workers. Test it in the real environment. Always include a fallback: if new Worker throws, run the computation on the main thread in small slices. A game that works slowly is better than a game that does not start. See also which files a PlayKovo zip may contain.
Good candidates, and bad ones
Good: level generation and solvability checks (see arrow puzzle generators), pathfinding on big grids (A* on a grid), flood fills for large maps, procedural terrain, AI search for board games.
Bad: anything under about 5 milliseconds, which costs more in messaging than it saves, anything that needs the canvas and anything that must run in lock-step every frame.
Measure first
Before moving code to a worker, measure it with performance.now() on a low-end phone. If it takes 2 ms there, a worker is unnecessary complication. If it takes 80 ms, it will cause a visible dropped frame at 60 Hz (16.7 ms per frame), and a worker will fix it. Use the Performance panel in DevTools with CPU throttling to see the long task that blocks input. Fix what you measured, not what you assumed.


