可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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??::::
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;
}
}
回答1:
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;
}
);
回答2:
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/
回答3:
This will not give accurate timings because javascript uses an event queue. That means your program may execute like this:
- Start AJAX request
- Handle a waiting mouse click event / any other waiting line of code in the meantime
- Start handling the AJAX ready response
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/.
Html:
<a href="#">link</a>
<div></div>
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();
}
});
回答4:
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.
The current stable version of jQuery (at time of writing: 2.2.2) has a beforeSend
key which accepts a function. I would do it there.
Note that in JavaScript, all globally scoped variables that are declared outside of a function are initialized as soon as the program starts up. Understanding JavaScript scope will help here.
The tricky part is accessing the variable you declared in the beforeSend
function in the success
callback. If you declare it locally (using let
) you can't easily access it outside of that function's scope.
Here is an example which will give slightly more accurate results (caveat: in most cases!) which is also dangerous since it declares a globally scoped variable (start_time
) which could interact badly with other scripts on the same page, etc.
I would love to dive into the world of JavaScript's prototype bind function but it's a bit out of scope. Here is an alternate answer, use with care, and outside of production.
'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));
}
]);
回答5:
You can set the start time to a var and calculate the time difference when the AJAX action completed.
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.
回答6:
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
回答7:
How About This:
First Globally Set the property TimeStarted
with the request object.
$(document).ajaxSend(function (event, jqxhr, settings) {
jqxhr.TimeStarted = new Date();
});
And then call any ajax
var request = $.ajax({
async : true,
success : function(){
alert(request.TimeStarted);
},
});
回答8:
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
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);
}
});