I was reading up on this javascript tutorial:
http://www.switchonthecode.com/tutor…ccordion-menus
Basically, it shows you how to create an accordion using pure javascript, not jquery. All made sense to me until the actual part of tracking the animation. He says “Because of all that, the first thing we do in the animation function is figure out how much time has passed since the last animation iteration.”
And then uses this code:
Code:
var elapsedTicks = curTick - lastTick;
lastTick is equal to the value of when the function was called (Date().getTime()) and curTick is equal to the value when the function was received. I don’t understand why we are subtracting one from the other right here. I can’t imagine that there’s any noticeable time difference between these two values. Or maybe I’m missing something. Is that animate() function only called once every time a menu title is clicked or is it called several times to create the incremental animation effect?
setTimeout("animate(" + new Date().getTime() + "," + TimeToSlide + ",'" + openAccordion + "','" + nID + "')", 33);
Thanks for any response.
lastTickis equal to the value when the function was previously called, on the last frame of animation. Since then, the script has given control back to the browser, asking to be called back in 33 milliseconds.So
curTick-lastTickwill generally be about 33, but it could be much higher if the browser is lagged due to other stuff happening at the same time. This is why time-reading has to be done at all.More usually in this sort of code, you’d store the time the animation started in a variable, and use
setIntervalto check it every so often, instead of setting a complete new timeout function each time (especially setting a timeout from a string, which is super-ugly).eta:
Nope. Look at the set-timeout call again:
That’s making a string.
new Date().getTime()is evaluated at timeout-setting time, not at timeout-calling time. It ends up making a string like:Which is the time at the end of the last frame, not the time the next frame’s timeout will fire.
Putting JavaScript code in a string like this is super-confusing, rife with escaping problems, and generally regarded as really poor practice. It would be clearer to do it with an inline function: