有一个只有一条路由的 React 应用程序。我发出了几个 API 请求以从后端获取数据。在获取时,我显示在成功请求后加载微调器和实际数据。我需要获取以毫秒为单位的时间,获取所有文件(如 js 文件等)、发出请求和显示数据花费了多少时间。我怎样才能做到这一点?我看到有 Performance API,但它似乎已被弃用。
我尝试使用 Performance API,但它已被弃用。
当然!您确实可以使用 getTime 函数获取 API 调用前后的时间戳来计算 API 响应时间。
const startTime = new Date().getTime();
fetch('your-api-endpoint')
.then(response => response.json())
.then(data => {
const endTime = new Date().getTime();
const apiResponseTime = endTime - startTime;
console.log("res:", apiResponseTime, "ms");
})
.catch(error => {
console.error('err', error);
});