setTimeout within function fails
Question by user1019490
This function accepts an argument, whichImage. This is the object HTMLImageElement for the image we are working with. The image width will be halved, and then after 3 seconds, it will return to normal width. However, the setTimeout code, which is supposed to execute after 3 seconds, fails, with the error message that whichImage is not defined. What do I need to correct to make this function work?
function resizeImageFunction(whichImage){
// Get the width of the image
alert(whichImage);
var width = whichImage.width;
var halfwidth = Math.round(width/2);
whichImage.width=halfwidth;
setTimeout("whichImage.width=width;",3000);
}
Answer by Starx
You don’t need to use eval for this
setTimeout(function() { whichImage.width=width; } ,3000);
Here is is your function
function resizeImageFunction(whichImage){
var halfwidth = Math.round(width/2);
whichImage.width=halfwidth;
setTimeout(function() { whichImage.width=width; } ,3000);
}