Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to measure timing of mulitple ajax calls if javascript is single threaded

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.

like image 491
Alex Avatar asked Dec 14 '25 01:12

Alex


1 Answers

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.

like image 57
shennan Avatar answered Dec 15 '25 15:12

shennan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!