I recently asked a question about the same function, that solved my probelem and directed me to a tutoraial because I was using a while loop, this meant that my function did not animate, just freeze then resize. This new way, using setTimeout should work. The only thing is that it just snaps to the new size rather than animating to it. There are no errors according to firebug. Here is my current section of code that manages the animation.
// Resize in timeframe
// Work out distance
var widthdiff = width - parseInt(element.style.width);
var heightdiff = height - parseInt(element.style.height);
// Work out how miliseconds per step (100 in total)
var steptime = timeframe / 100;
// Work out how many pixels it needs to move each step
var widthpps = widthdiff / 100; // ERROR?
var heightpps = heightdiff / 100;
// Set up original sizes
var origwidth = parseInt(element.style.width);
var origheight = parseInt(element.style.height);
// Loop through all 100 steps setting a time out resize each time
var timers = [];
for(var i = 0; i < 100; i++)
{
timers[i] = setTimeout(function() { // ERROR?
element.style.width = origwidth + (widthpps * i) + 'px';
element.style.height = origheight + (heightpps * i) + 'px';
}, i * steptime);
}
The arguments are being passed fine, I have tested all that and I had it animating once, just wrong. So my problem will lie close to the comments called ERROR? I beleive. Thanks for any help.
The problem is that the variable “i” will be shared by all the timeout functions.
You can write a separate function to build your timeout functions, or you can wrap the function in-line:
When I say that “i” will be “shared”, what I mean is that each of those functions you build in the loop will correctly refer to that loop variable. But what’s happening to that variable? It’s changing on each iteration of the loop. It’s important to understand that the functions will reference the real “i” variable, not a frozen copy. By using a second function, as I did above, you make a copy of the “i” used in the loop.