0

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.

4

1 回答 1

0

lastTick 等于函数调用时的值

lastTick等于之前在动画的最后一帧调用函数时的。从那时起,脚本将控制权交还给浏览器,要求在 33 毫秒内回调。

因此curTick-lastTick通常约为33,但如果浏览器由于同时发生的其他事情而滞后,则可能会更高。这就是为什么必须进行时间阅读的原因。

更常见的是,在这种代码中,您会将动画开始的时间存储在一个变量中,并setInterval经常使用它来检查它,而不是每次都设置一个完整的新超时函数(尤其是从字符串设置超时,这超级丑)。

埃塔:

然后运行 ​​animate() 函数,该函数传递当前时间

没有。再次查看 set-timeout 调用:

setTimeout("animate(" + new Date().getTime() + ","...

那是做一个字符串。new Date().getTime()在超时设置时间而不是在超时调用时间进行评估。它最终制作了一个字符串,例如:

setTimeout("animate(1275139344177, 250, 'Accordion4Content', 'Accordion4Content')", 33)

这是最后一帧结束的时间,而不是下一帧超时的时间。

像这样将 JavaScript 代码放在一个字符串中是非常令人困惑的,充满了转义问题,并且通常被认为是非常糟糕的做法。使用内联函数会更清楚:

var passTick= new Date().getTime();
setTimeout(function() {
    animate(passTick, TimeToSlide, openAccordion, nID);
}, 33);
于 2010-05-29T12:20:31.457 回答