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.
Page code · sequential
Task code · separate from the page
generateMap()Calculate the mapSome code preparation and garbage-collection work.
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.