0

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

Anthony Lee
  • 223
  • 1
  • 6
  • 14

1 Answers1

1

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/

Community
  • 1
  • 1
Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307