Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript timer not correct

I'm trying to time a ajax request, but I get random elapsed time:

startTime = new Date();  

$.ajax({
 ...
 success: function(response){

   endTime = new Date();
   timeDiff = endTime - startTime; 
   elapsed = Math.round(timeDiff % 60);

   alert(elapsed + ' seconds elapsed');
 }
}

...Like after 2 seconds I get 36 seconds, or 59 seconds, or 1 second etc..

What am I doing wrong here?

like image 488
A-- Avatar asked Dec 12 '25 15:12

A--


1 Answers

Use / instead of %

% is modulo operator.

Proper code to calculate number of seconds between to dates:

(endTime.getTime() - startTime.getTime()) / 1000
like image 79
Jakub Konecki Avatar answered Dec 14 '25 03:12

Jakub Konecki



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!