Javascript 找出完成 Ajax 请求所需的时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3498503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:55:07  来源:igfitidea点击:

Find out how long an Ajax request took to complete

javascriptjqueryxmlhttprequest

提问by Chris Dutrow

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

找出特定$.ajax()请求花费了多长时间的好方法是什么?

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

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

ANSWER??::::

回答??::::

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...:

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

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;
    }
}

采纳答案by Isaac

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

@codemeit 是对的。他的解决方案类似于以下使用 jQuery 处理 ajax 请求的方法。这以毫秒为单位返回请求时间。

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

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

回答by Anonymous

This is the proper way to do it.

这是正确的做法。

$.ajax({
    url: 'http://google.com',
    method: 'GET',
    start_time: new Date().getTime(),
    complete: function(data) {
        alert('This request took '+(new Date().getTime() - this.start_time)+' ms');
    }
});

https://jsfiddle.net/0fh1cfnv/1/

https://jsfiddle.net/0fh1cfnv/1/

回答by Aristoteles

This will not give accurate timings because javascript uses an event queue. That means your program may execute like this:

这不会给出准确的时间,因为 javascript 使用事件队列。这意味着您的程序可能会像这样执行:

  • Start AJAX request
  • Handle a waiting mouse click event / any other waiting line of code in the meantime
  • Start handling the AJAX ready response
  • 启动 AJAX 请求
  • 同时处理等待的鼠标单击事件/任何其他等待的代码行
  • 开始处理 AJAX 就绪响应

Unfortunately there is no way to get the time the event was added to the queue as far as I know. Event.timeStamp returns the time the event was popped from the queue, see this fiddle: http://jsfiddle.net/mSg55/.

不幸的是,据我所知,没有办法获得事件被添加到队列中的时间。Event.timeStamp 返回事件从队列中弹出的时间,请参阅此小提琴:http: //jsfiddle.net/mSg55/

Html:

网址:

<a href="#">link</a>
<div></div>

Javascript:

Javascript:

$(function() {
    var startTime = new Date();
    $('a').click(function(e) {
        var endTime = new Date(e.timeStamp);
        $('div').append((endTime - startTime) + " ");
        //produce some heavy load to block other waiting events
        var q = Math.PI;
        for(var j=0; j<1000000; j++)
        {
            q *= Math.acos(j);
        }
    });

    //fire some events 'simultaneously'
    for(var i=0; i<10; i++) {
        $('a').click();
    }
});

回答by GrayedFox

Aristoteles is right about the event queue. What you can do is slip your timestamp creation into a section of code you know will be executed as close as possible to the beginning of the AJAX request.

亚里士多德关于事件队列是正确的。您可以做的是将您的时间戳创建插入到您知道将在尽可能接近 AJAX 请求开始处执行的代码部分中。

The current stable version of jQuery (at time of writing: 2.2.2) has a beforeSendkey which accepts a function. I would do it there.

jQuery 的当前稳定版本(在撰写本文时:2.2.2)有一个beforeSend接受函数的键。我会在那里做。

Note that in JavaScript, all globally scoped variables that are declared outside of a functionare initialized as soon as the program starts up. Understanding JavaScript scope will help here.

请注意,在 JavaScript 中,所有在函数外部声明的全局范围变量都会在程序启动后立即初始化。理解 JavaScript 作用域会有所帮助。

The tricky part is accessing the variable you declared in the beforeSendfunction in the successcallback. If you declare it locally (using let) you can't easily access it outside of that function's scope.

棘手的部分是访问您beforeSendsuccess回调函数中声明的变量。如果您在本地(使用let)声明它,则无法在该函数的范围之外轻松访问它。

Here is an example which will give slightly more accurate results (caveat: in most cases!) which is also dangeroussince it declares a globally scoped variable (start_time) which could interact badly with other scripts on the same page, etc.

这是一个示例,它会给出更准确的结果(警告:在大多数情况下!)这也很危险,因为它声明了一个全局范围的变量(start_time),该变量可能与同一页面上的其他脚本等交互不良。

I would love to dive into the world of JavaScript's prototype bindfunction but it's a bit out of scope. Here is an alternate answer, use with care, and outside of production.

我很想深入研究 JavaScript 原型绑定函数的世界,但它有点超出范围。这是一个替代答案,请谨慎使用,并在生产之外使用。

'use strict';
$.ajax({
    url: url,
    method: 'GET',
    beforeSend: function (request, settings) {
        start_time = new Date().getTime();
    },
    success: function (response) {
        let request_time = new Date().getTime() - start_time;
        console.log(request_time);
    },
    error: function (jqXHR) {
        console.log('ERROR! \n %s', JSON.stringify(jqXHR));
    }
]);

回答by Ray Lu

You can set the start time to a var and calculate the time difference when the AJAX action completed.

您可以将开始时间设置为 var 并计算 AJAX 操作完成时的时间差。

You can utilise Firefox plug-in Firebug to check the performance of the AJAX request and response. http://getfirebug.com/Or you could utilise Charles proxy or Fiddler to sniff the traffic to see the performance etc.

您可以利用 Firefox 插件 Firebug 来检查 AJAX 请求和响应的性能。http://getfirebug.com/或者您可以使用 Charles 代理或 Fiddler 来嗅探流量以查看性能等。

回答by Bimal Das

How About This:

这个怎么样:

First Globally Set the property TimeStartedwith the request object.

首先全局设置TimeStarted请求对象的属性。

$(document).ajaxSend(function (event, jqxhr, settings) {
    jqxhr.TimeStarted = new Date();
});

And then call any ajax

然后调用任何ajax

var request = $.ajax({ 
    async : true,
    success : function(){
    alert(request.TimeStarted);
   },
});

回答by Yi-Yu Bruce Liu

I fiddled a bit and got a generic function that can be displayed for all ajax calls. This means that you don't have to do the same thing for every single ajax call

我稍微摆弄了一下,得到了一个可以为所有 ajax 调用显示的通用函数。这意味着您不必为每个 ajax 调用都做同样的事情

var start_time;   
$.ajaxSetup({
  beforeSend: function () {
    start_time = new Date().getTime();
  },
  complete: function () {
    var request_time = new Date().getTime() - start_time;
    console.log("ajax call duration: " + request_time);
  }
});

回答by Katta Nagarjuna

makeRequest = function(){

    // Set start time
    console.time('makeRequest');

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

getRquestSuccessFunction = function(start_time){

    console.timeEnd('makeRequest');

    return function(data, textStatus, request) {

    }
}

this gives output in mseconds like makeRequest:1355.4951171875ms

这以毫秒为单位提供输出,如 makeRequest:1355.4951171875ms