javascript 测量 AJAX 调用的处理时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5177451/
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
measure processing time of AJAX call
提问by Radek
I want to measure how long it takes to processAJAX call. I have it up and running but don't know how to code this in javascript (js only)
我想测量处理AJAX 调用需要多长时间。我已经启动并运行,但不知道如何在 javascript 中编写代码(仅限 js)
回答by Alex Wayne
var start = new Date().getTime();
doAjax({
success: function() {
var end = new Date().getTime();
console.log('milliseconds passed', end - start);
}
});
save a time value before you start doing ajax stuff, and then do it again when it finishes. Then subtract one form the other and get your time.
在开始做 ajax 之前保存一个时间值,然后在它完成时再做一次。然后从另一个中减去一个,然后花时间。
回答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();
}
});

