Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing a specific fetch call

I am making a fetch call like so fetch("foo.com/x.json") and would like to get the time it takes to make the request as it is reported in dev tools.

I have already tried,

performance.mark("fetch-start");
let start = performance.now();
let res = fetch("https://example.com/foo.json", {});
res.then(r => {
  performance.mark("fetch-end");
  performance.measure("fetch", "fetch-start", "fetch-end");
  var measures = performance.getEntriesByName("fetch");
  var measure = measures[0];
  console.log(measure);
});

Have also tried performance.now() -start and they are not as accurate as the devtools, I'm guessing this is due to the fact that the browser does more than one thing at once and doesn't spend all it's time measuring things in isolation.

Is there a way to get as accurate as Developer tools for network timing?

like image 642
Sevki Avatar asked Aug 21 '18 16:08

Sevki


2 Answers

There is a Resource Timing API being defined that will help us do just this.
Note that this is still a draft and prone to change in the future, but it's already available in the three main browser engines.

const url = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png?" + Math.random();
// create PerformanceObserver
const resourceObserver = new PerformanceObserver( (list) => {
  list.getEntries()
    // get only the one we're interested in
    .filter( ({ name }) => name === url )
    .forEach( (resource) => {
      console.log( resource );
    } );
  // Disconnect after processing the events.
  resourceObserver.disconnect();
} );
// make it a resource observer
resourceObserver.observe( { type: "resource" } );
// start the new request
fetch( url, { mode: "no-cors" } );
like image 191
Kaiido Avatar answered Oct 03 '22 14:10

Kaiido


Answer:

Try wrapping the code below in an async function and using performance.now()


Browser JavaScript

async function checkResponseTime(testURL) {
    let time1 = performance.now();
    await fetch(testURL);
    let time2 = performance.now();
    return time2 - time1;
}
console.log(await checkResponseTime('https://stackoverflow.com'))

Node.JS

let fetch = require('node-fetch');
async function checkResponseTime(testURL) {
    let time1 = performance.now();
    await fetch(testURL);
    let time2 = performance.now();
    return time2 - time1;
}
console.log(await checkResponseTime('https://stackoverflow.com'))
like image 40
quicVO Avatar answered Oct 03 '22 15:10

quicVO