What is the typical response time for a request using javascript axios?

In my current application, I am fetching data from an API and everything is functioning correctly. However, I am interested in determining the duration of each request in milliseconds. To achieve this, I implemented interceptors using axios. The challenge I am facing is that the time value I receive under request-duration is only available after the request has been responded to, which is not what I need. I want to capture the time either before or during the call to the webservice. Complicating matters further is the fact that the method I invoke is located in a separate file: Request.js

export const getRequest = async (url, baseURL, headers) => {
  const HTTP = axios.create({
    baseURL,
    headers,
  });
  HTTP.interceptors.request.use((config) => {
    config.headers["request-startTime"] = new Date().getTime();
    return config;
  });
  HTTP.interceptors.response.use((response) => {
    const currentTime = new Date().getTime();
    const startTime = response.config.headers["request-startTime"];
    response.headers["request-duration"] = currentTime - startTime;
    return response;
  });
  return HTTP.get(url);
};

Users.vue

async getUsers() {
  try {
    let url = `/users`;
    let baseUrl = `baseURL`;
    let headers = {};
    const responseUsers = await getRequest(url,baseUrl,headers); 
    console.log(responseJobTasks.headers["request-duration"]); //displays the time in milliseconds here
    if (responseJobTasks.status === 200) {
      const { data } = responseJobTasks;
      this.users = data;
    }
  } catch (error) {
    console.error(error);
  }
}

Answer №1

To determine the time it takes for a request to complete, you can simply compare the timestamps before and after:

let startTime = Date.now();
let responseData = await makeRequest(url);
let endTime = Date.now();
let duration = endTime - startTime;

Alternatively, you could utilize the User Timing API, although it may be excessive for measuring the timing of just one request.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display only the selected index and conceal the rest

I am facing an issue where I have added a label and input in ng-repeat. The functionality works fine when the user clicks edit to show the input and hide the label. However, the problem arises when the user clicks on the new button as it displays the new i ...

Ways to implement a percentage for scrollTop

I'm currently troubleshooting the code below. My goal is to understand why I'm unable to scroll the .post div with jQuery and input range properly using a percentage value like this: $("[type=range]").on('input',function(){ var v ...

Modifying properties within child components

Within my parent Vue Page, I have inserted a FormInput component inside my form. new.vue <b-form @submit.prevent="submit"> <FormInput :name="name"/> <b-button @click="submit">Save</b-button> <b-form> <script> i ...

Scroll up and down to witness the enchanting interplay of fading in and out

Looking to expand upon the solution given in this response. The existing code effectively fades in an element while scrolling down and fades out an image when scrolling up; however, it lacks the functionality to fade out when scrolling down. I am aiming ...

What is the best way to incorporate user input and output functionality in a React Javascript application with Material UI for a seamless display?

I am trying to achieve a similar output as shown in this code http://jsfiddle.net/6vqd4vnq/ but using material ui/reactjs. Is there something missing in my setup that is preventing the content from being displayed correctly like in the provided link whic ...

Changing the value of undefined properties in a JavaScript object

I am struggling to identify and replace null values with 0's in my object. I was able to access the correct member within the loop, but once it exited, the values were no longer assigned as 0. Working with objects in JavaScript is new to me, so I&apos ...

Testing Your Angular 7 Code: Unit Testing Made Easy

I am currently working on developing unit tests for this angular script: export class DataService { private csrfToken: string = ''; private isContentShown: BehaviorSubject<boolean> = new BehaviorSubject(true); constructor(private h ...

Are you experiencing issues with modal contents extending beyond the modal on smaller screens?

I recently installed a modal plugin called blockUI for my image uploading needs. Although I have styled and positioned everything accordingly, I am facing an issue: Whenever I resize the browser screen, switch to my iPhone, or use another screen, some con ...

What could be causing req.body to consistently come back as an empty object?

I am struggling with req.body always returning an empty object regardless of what I try. I have experimented with: var jsonParser = bodyParser.json(); and then including jsonParser in the function -> app.post('/api/get-last-project',jsonParser ...

Determine image size (pre-upload)

One of the requirements for a project I am working on is to verify the dimensions (width and height) of images before uploading them. I have outlined 3 key checkpoints: 1. If the dimensions are less than 600 X 600 pixels, the upload should be rejected. ...

Cannot render <Image> inside <Section> component

As a beginner in React, I am attempting to create an app following a tutorial. In my component, I utilized the figure tag but it's not showing up when inspecting element in Chrome. Here are the code snippets: The tutorial includes a div tag as a chil ...

Can Next.js 13 components maximize performance by utilizing server and client components simultaneously? What is the best approach to achieve this?

Introduction Currently, I am exploring server and client components in Next.js 13 and looking to incorporate them into my project. One of the key features is a container component that utilizes react-intersection-observer to track which section is visible ...

Fetching data using an Ajax request in PHP is encountering issues, whereas the same request is successfully

I am experiencing an issue with a simple Ajax call in ASP.NET that works fine, but encounters a strange DOM Exception when I insert a breakpoint inside the onreadystatechange function. Can anyone explain why ASP.NET seems to have some additional header log ...

"Upon completing an AJAX file upload, both $_POST and $_FILES arrays are found

Recently, I've delved into the realm of web development and encountered a hurdle with ajax file uploading... My current setup involves two HTML input fields: one for files and another for a button. <input type="file" name="Frame" id=" ...

Is the next function triggered only after the iframe has finished loading?

First and foremost, I understand the importance of running things asynchronously whenever possible. In my code, there exists a function known as wrap: This function essentially loads the current page within an iframe. This is necessary to ensure that Jav ...

JavaScript regex substitution not functioning as expected

My JavaScript code contains a string var str = '<at id="11:12345678">@robot</at> ping'; I am trying to remove a specific part of this string <at id="11:12345678">@ To achieve this, I am using the following code snippet: var ...

Check to see if the property of the object does not exist within the array and update as

My goal is to add the variable content into the database content using the $push method, but only if the content.hash doesn't already exist in the database. I want to avoid duplicating information unnecessarily. return shops.updateAsync({ "user": u ...

Analyzing the browser's address bar and creating a navigation link derived from it

Is there a way to create a script that can extract information from the address bar? For example, if we have a link like this: We want to be able to take the "page-2011" part and dynamically generate navigation links like this: « <a href="/page-2010 ...

In JavaScript, the "this" keyword points to a different object

Here is a script that needs attention: Bla = function() { this.prop = 123; } Bla.prototype.yay = function() { console.log(this,this.prop); } X = new Bla(); $(document).ready(X.yay); // output: #document undefined --> why? $(document).ready(functio ...

Strange symbols were stored in the database after saving the textarea value

After submitting a form, text entered into a text area is being saved to my database. However, in one instance, certain characters such as • are appearing in the field. For example: • Text When retrieving the data from the database using Jav ...