Reputation: 33
I've got this function:
function zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight){
var widthStep = (targetWidth - currentWidth) / 100;
var heightStep = (targetHeight - currentHeight) / 100;
var newWidth = Math.ceil( currentWidth + i * widthStep );
var newHeight = Math.ceil( currentHeight + i * heightStep );
i++;
var imageZ = document.getElementById(image);
imageZ.style.width = newWidth+"px";
imageZ.style.height = newHeight+"px";
while( i <= 100 )
t = setTimeout("zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight)",10);
}
Called like this:
zoomImage(0, "image1", 200, 150, 260, 195);
But for some reason the page won't stop loading and crashes eventually. Also the image doesn't get bigger. What am I doing wrong here?
Upvotes: 1
Views: 166
Reputation: 11327
I assume you initialized i
outside the function. That's the i
that will always get passed in when you make your recursive call. This is because when you give a string to setTimeout
, it is evaluated in the global scope.
This means that the i++
inside the function only affects the local i
, and not the global i
, so i
is never incremented not incremented beyond 1 + the global value.
Instead pass an anonymous function that invokes the recursive call. This way you're actually passing the incremented i
.
while( i <= 100 )
setTimeout(function() {
zoomImage(i, image, currentWidth, currentHeight, targetWidth, targetHeight);
},10);
Of course, as noted in the comments, while
doesn't seem like the right choice here.
Upvotes: 3