3

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?

3 Answers 3

2

Use / instead of %

% is modulo operator.

Proper code to calculate number of seconds between to dates:

(endTime.getTime() - startTime.getTime()) / 1000
Sign up to request clarification or add additional context in comments.

Comments

1

Date - Date returns milliseconds. Lets say your request takes one second, so timediff = 1000. You then do a 1000 % 60, which is 40 and not what you want...

I think you want this:

elapsed = Math.round(timeDiff / 1000);

Which will convert milliseconds to seconds.

The modulo operator % return the remainder of a division operation which is not something you appear to be after...

http://en.wikipedia.org/wiki/Modulo_operation

Comments

0

Add a + sign to both versions of new Date():

startTime = +new Date();

That will guarantee that the date is converted into a numerical value (timestamp) which you can do the substraction operation with. It looks like it does work without, but I don't know what that will do some in browsers/versions implementations.

Also as mentioned in other answers, you need to divide the result (which is in miliseconds) by 1000 to get the seconds.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.