Anthony Lee
Anthony Lee

Reputation: 243

measure processing time of multiple AJAX calls at the same page

In this way I can measure the processing time of mine ajax call

var ajaxTime= new Date().getTime();
$.ajax({
    type: "POST",
    url: "some.php",
}).done(function () {
    var totalTime = new Date().getTime()-ajaxTime;
    // Here I want to get the how long it took to load some.php and use it further
});

but, how can I do if I want get the processing time for multiple ajax call at the same page?

I mean something like this:

var i;
var j = 5;
for (i = 0; i < j; i++) {
var ajaxTime= new Date().getTime();
$.ajax({
    type: "POST",
    url: "some.php",
}).done(function () {
    var totalTime = new Date().getTime()-ajaxTime;
    // Here I want to get the how long it took to load some.php and use it further
});
}

I need to know the response time for each call

Upvotes: 0

Views: 468

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126072

Your problem is that there's no block scope in JavaScript, so ajaxTime is not redeclared on every loop iteration (it's set to whatever the current time is on each iteration). You can refactor your $.ajax code into a function or use a closure so that a new ajaxTime variable is used for every request:

var i;
for (i = 0; i < 5; i++) {
    makeRequest(i);
}

function makeRequest(i) {
    var ajaxTime = new Date().getTime();
    $.ajax({
        url: 'some.php',
        type: 'POST'
    }).done(function () {
        var total = new Date().getTime() - ajaxTime;
        console.log('Elapsed time: ' + total);
    });
}

Example: http://jsfiddle.net/Y9MJk/1/

Upvotes: 1

Related Questions