Reputation: 892
var startTime = new Date().getTime();
var ajaxResponseTime1;
var ajaxResponseTime2;
$.ajax({
success: function(){
ajaxResponseTime1= new Date().getTime() - startTime;
//some task that takes 5 seconds
}
});
$.ajax({
success: function(){
//possibly inaccurate since it includes the time it took to
//execute other success callback function
ajaxResponseTime2= new Date().getTime() - startTime;
//some task that takes 5 seconds
}
});
Since javascript is single threaded, doesn't that mean that whichever success method gets called first, the time it took to execute that success method will be figured into the time it took the 2nd success callback function to be called?
I want to know the time it took each ajax call to call the success callback. As in the response time.
Upvotes: 3
Views: 152
Reputation: 11676
I'm re-editing this answer now that I have more of an understanding of how you're approaching your question.
The term accuracy is obviously relative. The two ajax calls are called less than a millisecond apart on most modern processors. Consider this code:
var start = new Date.getTime();
display();
function display(){ console.log(new Date().getTime() - start); };
The resulting output will likely be 0. That's 0 milliseconds. What does this tell us about the execution time of an arbitrary method?
Yes JavaScript is single-threaded. Yes it's synchronous. So the fact is that one method will always call before the other, despite them coming in at the same time.
However, the response times will be 'pretty' accurate so long as the callbacks don't bottleneck the scripts execution. As I said, it depends what you call 'acurate'.
Another Edit!
Dang it. I've just noticed your //some task that takes 5 seconds
comment is possibly referring to a long synchronous task? If you are saying that the process will execute for 5 seconds, synchronously, then yes - accuracy will be an issue here.
Upvotes: 1
Reputation: 892
var startTime = new Date().getTime();
var ajaxResponseTime1;
var ajaxResponseTime2;
var executeTime = 0;
$.ajax({
success: function(){
ajaxResponseTime1= new Date().getTime() - startTime - executeTime;
//some task that takes 5 seconds
executeTime = new Date().getTime() - ajaxResponseTime1;
}
});
$.ajax({
success: function(){
ajaxResponseTime2= new Date().getTime() - startTime - executeTime;
//some task that takes 5 seconds
executeTime = new Date().getTime() - ajaxResponseTime2;
}
});
Now the execution time of any other callbacks is considered when getting the response time.
Upvotes: 0