Threads16 / 19

JavaScript threads

Where page code runs and what a Web Worker is for.

A thread executes code sequentially. Page code usually runs on the browser’s main thread, where game logic and input handlers execute.

If a long calculation runs on this thread, such as map generation, click handlers must wait for it to finish. The game may stop responding to player input as a result.

Browser
Main thread

Page code · sequential

Process input
Update the game
Task →← ResultMessages
Worker thread

Task code · separate from the page

generateMap()Calculate the map
V8 background threads

Some code preparation and garbage-collection work.

The main thread and a Worker can run at the same time. Within each thread, code runs sequentially.

V8 also has its own background tasks, such as preparing code and some garbage-collection work. The engine schedules these tasks itself. To move a game function to another thread, the application must create a Worker and run the code there.

What async does

A function declared with async returns a Promise.

async function buildMap() {
  return generateMap(); // Still runs on the calling JS thread
}

Here, generateMap() runs on the same thread that called buildMap(). If the calculation takes a long time, the thread stays busy throughout. Adding async does not move the calculation to a Worker.

Key takeaway

Code on one thread runs sequentially. A Web Worker runs JavaScript separately. async alone does not move computation to another thread.

Check the primary source ↗

HTML Standard · Web Workers↗Running JavaScript separately and exchanging messages with the page.ECMA-262 · AsyncFunctionStart↗Calling an async function begins executing its body on the current thread.ECMA-262 · Promise Objects↗A Promise represents an operation's result or failure.V8 · Background compilation↗The engine can perform some code preparation on a background thread.V8 · Orinoco GC↗Some garbage-collection work can run in the background.