找出完成一个 Ajax 请求需要多长时间

2022-01-15 00:00:00 xmlhttprequest jquery javascript

找出特定 $.ajax() 请求所用时间的好方法是什么?

What is a good way to find out how long a particular $.ajax() request took?

我想获取此信息,然后将其显示在页面上的某处.

I would like to get this information and then display it on the page somewhere.

ANSWER??::::

我是 javascript 新手,如果您不想内联成功"函数(因为它将是一个更大的函数),这是我能想到的最好的方法.做这个?我觉得我把事情复杂化了……:

I'm new to javascript, this is the best that I could come up with if you don't want to inline the "success" function (because it will be a much bigger function) Is this even a good way to do this? I feel like I'm over complicating things...:

makeRequest = function(){
    // Set start time
    var start_time = new Date().getTime();

    $.ajax({ 
        async : true,
        success : getRquestSuccessFunction(start_time),
    });
}

getRquestSuccessFunction = function(start_time){
    return function(data, textStatus, request){
        var request_time = new Date().getTime() - start_time;
    }
}

推荐答案

@codemeit 是对的.他的解决方案如下所示,使用 jQuery 处理 ajax 请求.这会以毫秒为单位返回请求时间.

@codemeit is right. His solution looks something like the following using jQuery for the ajax request. This returns the request time in milliseconds.

var start_time = new Date().getTime();

jQuery.get('your-url', data, function(data, status, xhr) {
        var request_time = new Date().getTime() - start_time;
});

相关文章