A page stalls after a click: using Fetch timing and JS Self-Profiling to distinguish a slow request from slow JavaScript

May 14, 2025

While writing a logger for an HTTP client, I recorded a time before and after calling fetch. The console could report “180 ms” and the user could still wait over a second before seeing a list. Both measurements can be right. To explain the gap, first ask where the 180 ms clock stopped and when there was actually something on screen to see.1

When await fetch() returns, what has the user waited for?

Suppose we start timing when the user clicks “Load assets” and obtain the following timeline. The numbers are illustrative. The last row assumes we separately confirmed that frame in a browser performance recording.

Time since clickWhat happenedWhat this tells us
0 msClick handler starts and calls fetch immediatelyThe wait for the endpoint begins.
180 msawait fetch() returns a ResponseStatus and headers are available. My logger stops here.
700 msawait response.json() completesParsed data is now available. The 520 ms since the previous row includes both waiting for the body and parsing it. We don’t yet know their individual shares.
1,260 msThe first asset-list frame appears on screenAnother 560 ms elapsed after the data became usable. Data formatting, DOM updates, layout, and painting may all contribute.

So don’t assign all 520 ms to JSON parsing. Browser Resource Timing provides responseEnd, roughly when the browser received the final byte. Compare it with the application’s “parsing finished” timestamp to narrow the investigation. Calling setState or assigning to the DOM marks submission of an update. Determining when users actually saw the list needs evidence of the frame being presented.23

Is the API slow, or is the page still busy after the data arrives?

First divide an operation into meaningful intervals. The example below records request start, headers readable, and list data usable. It assumes a successful JSON response. Here performance.now() simply reads the current page’s monotonic clock. Chrome, Edge, Firefox, and Safari all support it. Subtracting two readings measures elapsed milliseconds, including time spent waiting on the network. Finding out which JavaScript functions executed calls for the stack sampling discussed below. Each invocation keeps its own timestamps in local variables, so even two simultaneous loads won’t get mixed up.4

async function loadAssets() {
  const start = performance.now();
  const response = await fetch('/api/assets');
  const headersReady = performance.now();
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  const assets = await response.json();
  const dataReady = performance.now();

  performance.measure('assets:headers', { start, end: headersReady });
  performance.measure('assets:read-and-parse', {
    start: headersReady,
    end: dataReady
  });
  return assets;
}

These two measurements stay in the browser performance timeline. To compare visits from many users, an SDK can record meaningful intervals as spans (steps with start and end times), connected by a trace for the operation as a whole. Sentry’s browser tracing can automatically record page loads, navigations, and requests. It also lets you instrument application steps such as preparing list data. If the endpoint itself is slow, instrument the frontend and backend to see whether the server was waiting on the database.5

How does JS Self-Profiling identify busy functions?

If the data has long been ready but the list still hasn’t appeared, examine what JavaScript was doing. The JS Self-Profiling API periodically takes call stack samples. Which function was executing at that moment, and who called it? If many samples follow “render asset row → format price → create formatter”, check whether every row repeats expensive initialization. Sampling points to hotspots. A function missing from the samples may simply have run to completion between two samples.6

A long span and a busy JavaScript function measure different things. A one-second wait for the server produces a one-second request span even if the main thread was idle. Conversely, if the data is back and samples keep pointing to the same formatting code, change that code and compare using the same data volume. If JS samples are sparse but presentation remains slow, inspect layout and paint activity in a browser performance recording.7

How do I collect a sample and read function names from it?

Suppose we want to know how many samples involve formatting asset prices. Start with the three central calls: the browser starts sampling as soon as the Profiler is created. Run the code you want to observe, then call stop() and retrieve the records for that period.8

const profiler = new Profiler({ sampleInterval: 10, maxBufferSize: 1000 });
formatAssetPrices();
const trace = await profiler.stop();

Here 10 requests one sample every 10 ms. Read profiler.sampleInterval for the interval the browser actually uses. 1000 is the sample buffer capacity. Save the complete local experiment below as profile.html. To give the sampler a chance to observe the work, the example deliberately creates a new currency formatter for every row in the loop.

<!doctype html>
<meta charset="utf-8">
<button id="run">采样一次价格格式化</button>
<pre id="output"></pre>
<script>
  const output = document.querySelector('#output');

  function formatAssetPrices() {
    let lastPrice;
    for (let i = 0; i < 5000; i++) {
      const formatter= new Intl.NumberFormat('zh-CN', {
        style: 'currency', currency: 'CNY'
      });
      lastPrice= formatter.format(i + 0.99);
    }
    return lastPrice;
  }

  document.querySelector('#run').onclick= async ()=> {
    if (typeof window.Profiler = 'function') {
      output.textContent= '此浏览器没有提供 Profiler。';
      return;
    }

    try {
      const profiler= new Profiler({ sampleInterval: 10, maxBufferSize: 1000 });
      const lastPrice= formatAssetPrices();
      const trace= await profiler.stop();

      let hits= 0;
      for (const sample of trace.samples) {
        // stackId 指向栈顶;沿 parentId 往上走,就能看到调用者。
        let stack= trace.stacks[sample.stackId];
        while (stack) {
          const frame= trace.frames[stack.frameId];
          if (frame.name= 'formatAssetPrices') {
            hits++;
            break;
          }
          stack= trace.stacks[stack.parentId];
        }
      }
      output.textContent= [
        '最后一行价格:' + lastPrice,
        '实际采样间隔:' + profiler.sampleInterval + ' ms',
        '总样本数:' + trace.samples.length,
        '调用栈含有 formatAssetPrices 的样本数:' + hits
      ].join('\n');
    } catch (error) {
      output.textContent= error.message;
    }
  };
</script>

To permit sampling on the local page, save these lines as serve.cjs in the same directory, run node serve.cjs, and open http://127.0.0.1:8000/ in a supporting Chrome or Edge version. The little server adds the required response header to the HTML document.9

const http = require('node:http');
const fs = require('node:fs');
const page = fs.readFileSync(__dirname + '/profile.html');
http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8',
    'Document-Policy': 'js-profiling' });
  res.end(page);
}).listen(8000, '127.0.0.1');

On one click in my local Chromium, the actual interval was 10 ms. I got 12 samples, 10 of whose stacks included formatAssetPrices. Even if a sample lands inside the formatter, it counts once if the caller stack contains formatAssetPrices. This means how often sampling found execution on this call path. The loop ran 5,000 times, but the hit count depends on machine speed and the sampling interval. Next, move new Intl.NumberFormat(...) outside the loop and click again. Use the ordinary timing from above as well to compare total time for the same work.

Do I need Playwright to capture this data?

The page can do it itself. The specification describes letting a web app control “a sampling profiler for measuring client JavaScript execution times”. In supporting browsers a page creates a Profiler and retrieves the samples afterwards, and a monitoring SDK can do this on the app’s behalf. Those samples describe execution on real visitors’ devices. Playwright is suited to repeating the same steps in a controlled browser, for example fixing the row count, comparing before and after a change, and reviewing a slow recording with browser performance tools.67

On May 14, 2025, I followed Sentry’s React profiling docs to the specification, then searched for the API again a few minutes later and went straight to MDN’s compatibility table. There really is a deployment requirement here. According to the Sentry browser docs I consulted, function sampling requires configuring browser profiling in the SDK and returning Document-Policy: js-profiling in the response headers for the HTML document that hosts the application. Sentry listed the feature as Beta and collected samples only in Chromium browsers supporting the API. Adding the header only to JSON responses won’t help. Ordinary request timing and tracing work independently, so you can receive a slow request trace without receiving function samples from that visitor.9

Back to the original 180 ms: I’d label the logger field “request sent to response headers received”. To explain the extra second before the list appeared, separately mark when the data became usable and inspect what the main thread and renderer did in the remaining time. To find out whether users saw an overlay or clicked again during that second, see Session replay. To investigate a 401, a 500, or a script exception during that operation, see What the page, HTTP client, and Playwright can each collect.

References

Footnotes

  1. Cai, B. [S2thend]. (2025, May 13). Express HTTP Client [源码,提交 7357757]. GitHub. Fetch 调用前后的计时位置。 ↩

  2. MDN contributors. (n.d.). Using the Fetch API. MDN Web Docs. Handling the response。 ↩

  3. MDN contributors. (n.d.). PerformanceResourceTiming: responseEnd property. MDN Web Docs. Value。 ↩

  4. MDN contributors. (n.d.). Performance: now() method;Performance: measure() method. MDN Web Docs. 单调时钟和浏览器支持、起止位置和返回值。 ↩

  5. Sentry. (n.d.). Application Performance Monitoring & Error Tracking Software. Sentry. 当时访问的产品介绍页,Tracing 锚点。Sentry. (n.d.). Set up tracing for React. Sentry Docs. 浏览器自动追踪、手动添加 span 与回放关联。 ↩

  6. Web Platform Incubator Community Group. (n.d.). JS Self-Profiling API. WICG. Abstract,第 1 段。MDN contributors. (n.d.). JS Self-Profiling API. MDN Web Docs. 调用栈采样及兼容性。 ↩ ↩2

  7. Chrome for Developers. (n.d.). Performance features reference. Main track。 ↩ ↩2

  8. Web Platform Incubator Community Group. (n.d.). JS Self-Profiling API. WICG. Profiler 接口、采样参数与数据结构。 ↩

  9. Sentry. (n.d.). Set up profiling for React. Sentry Docs. 支持范围、响应头与 SDK 配置。文档与兼容性按文首核对日期说明。 ↩ ↩2

© 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-05-14). A page stalls after a click: using Fetch timing and JS Self-Profiling to distinguish a slow request from slow JavaScript. https://caiborui.com/blog/2025-05-14-zh-fetch-timing-js-self-profiling-entrans

@misc{borui2025-72e4356a,
  author = {borui},
  title = {{A page stalls after a click: using Fetch timing and JS Self-Profiling to distinguish a slow request from slow JavaScript}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-05-14-zh-fetch-timing-js-self-profiling-entrans}
}