The JavaScript engine
Long tasks block the page
Understand why a long JavaScript function delays input handlers, timers, style work, layout, and painting.
8 minute lesson
The page’s main thread runs JavaScript and coordinates much of style calculation, layout, and painting. It can do only one piece of that work at a time.
button.addEventListener('click', () => {
const end = performance.now() + 500
while (performance.now() < end) {
// Simulate expensive synchronous work.
}
status.textContent = 'Done'
})
The DOM assignment is near the end of the handler, but the visitor sees no update until the task finishes and the browser gets another rendering opportunity. A second click also waits. This is why a page can look loaded and still feel frozen.
Performance tools commonly flag tasks longer than 50 milliseconds as long tasks. That is a diagnostic boundary, not a performance budget: several shorter tasks can still create a poor interaction.
Record the click in the Performance panel. Look for a wide task on the Main track and expand it until you find the function consuming the time. Then choose a fix that matches the work:
- remove calculations whose result is not needed
- use a better algorithm or process less data
- split deferrable work and yield so input and rendering can run
- move CPU-heavy work without DOM access to a Web Worker
Splitting work has overhead, and a worker adds messaging and data-transfer cost. Measure the complete interaction after the change. The goal is not merely a shorter function; it is a faster next paint and a responsive page.
Lesson completed