I am in the middle of writing a JavaScript library and I have hit a problem, I have a function that resizes elements, that all works good but I also have and animated version that resizes them over a specified time frame. The script seems to freeze when ever it is run and it seems to be down to my while loop, here is my code.
// Resize in timeframe
// Work out distance
var widthDiff = width - element.offsetWidth;
var heightDiff = height - element.offsetHeight;
// Work out pixels per milisecond
var widthppm = widthDiff / timeframe;
var heightppm = heightDiff / timeframe;
// Set up times
var d = new Date();
var endtime = d.getTime() + timeframe;
// Get the original width and height
var oldwidth = element.offsetWidth;
var oldheight = element.offsetHeight;
var iteration;
// Loop through until 开发者_JAVA百科done
while(d.getTime() >= endtime)
{
iteration = timeframe - (endtime - d.getTime());
element.style.width = oldwidth + (iteration * widthppm) + 'px';
element.style.height = oldheight + (iteration * heightppm) + 'px';
}
All I can tell you now are that the arguments (element, width, height, timeframe) are working fine, it is down to my algorithm. Any help will be great, thanks!
It should be d.getTime() <= endtime
.
Emphasis on <=
instead of >=
.
Additionally you need to get a new timestamp inside the loop, as the d.getTime()
will always be the same (the time at the moment it was created)..
so
while(d.getTime() <= endtime)
{
iteration = timeframe - (endtime - d.getTime());
element.style.width = oldwidth + (iteration * widthppm) + 'px';
element.style.height = oldheight + (iteration * heightppm) + 'px';
d = new Date();
}
But you should use a timeout/interval to animate and not a loop as that would block the rest of the scripts from executing..
Here are a couple of tutorials about animation with setTimeout
and setInterval
- http://www.schillmania.com/content/projects/javascript-animation-1/
- http://www.schillmania.com/content/projects/javascript-animation-2/
精彩评论