Click to See Complete Forum and Search --> : getTime() considered harmful


llanitedave
08-05-2004, 05:59 PM
It might just be me, but I can't figure it out. My getTime() code is inconsistent and inaccurate.

function mainLoop(lots, of, parameters)
{
var getStartTime = new Date().getTime();
while (notStoppedYet)
{
doLots(of, looping, complex, stuff);
checkSome(data);
....
}

// get the total time elapsed
var getStopTime = new Date().getTime();
var timePassed = getStopTime - getStartTime;
alert(timePassed);
}

I have checked this function numerous times with my handy-dandy wristwatch. It averages about 26 seconds to complete.

Yet my timePassed alert returns values like:
4,...6,...5,...

I thought (1) that the time would be in milliseconds. Obviously, it's not. Even so, (2)I can't figure out why it should be so inaccurate.

Can anybody imagine what I might be overlooking?

Thanks!

gil davis
08-05-2004, 07:48 PM
Javascript can sometimes start things and then go to the next statement. Perhaps that is why you get fast results.

BTW, it should definitely give you an answer in milliseconds.

BillyRay
08-06-2004, 04:45 AM
You don't say what type of activity you are performing in the "while" loop. However, I've found that certainly with rendering lots of content (so in my equivalent of your while loop, I scanned a complete directory tree, and wrote out 15000+ nodes) that the code finishes before the browser has totally updated its own internal DOM and also the screen.

In essence, my code finished after about 20 seconds, and that was the result the time calculations showed. However, IE didn't finish rendering the nodes until well after the function had finished, thus skewing the time completely.

AFAIK, there isn't an accurate way to control this behaviour with JavaScript, due to the way it runs.

Dan

llanitedave
08-06-2004, 01:31 PM
Thanks for the respnses, gil davis and BillyRay. Unfortunately, in this case I can't blame javascript. It was "Duh"!. I forgot that the "mainLoop()" function was recursive, and called itself after a setTimeout() condition. So, all I was getting was the final loop, because the start Time was re-initializing itself with every loop. I shouldn't have put it inside the function.

Oh, well. Another example of my programming lolgic genius!

BillyRay
08-06-2004, 01:46 PM
"This sort of thing has cropped up before and it has always been due to human error."

:D

llanitedave
08-06-2004, 02:01 PM
Who said that?

BillyRay
08-07-2004, 05:59 AM
It was HAL from the film "2001: A Space Odyssey"

:D

llanitedave
08-07-2004, 08:18 AM
Aaaaahhh...