【问题标题】:setTimeout within function fails函数内的 setTimeout 失败
【发布时间】:2012-03-25 06:02:09
【问题描述】:
这个函数接受一个参数,whichImage。这是我们正在使用的图像的对象 HTMLImageElement。图像宽度将减半,然后在 3 秒后恢复正常宽度。但是,应该在 3 秒后执行的 setTimeout 代码失败,并显示未定义 whichImage 的错误消息。我需要更正什么才能使此功能正常工作?
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);
}
【问题讨论】:
标签:
javascript
function
settimeout
【解决方案1】:
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(function(){
whichImage.width=width;
},3000);
}
【解决方案2】:
你的问题的解释如下:
当您将字符串传递给setTimeout() 时,该字符串将由eval() 在全局范围内进行评估。因此,您调用的任何函数或引用的变量都必须在全局范围内可用。这就解释了为什么你不能为你的函数引用一个局部变量或一个参数,因为它们都不在全局范围内,所以当eval() 试图找到它们时,它会在全局范围内查找它们不存在。
当您使用内联匿名函数将setTimeout() 函数更改为此时:
setTimeout(function() {
whichImage.width = width;
}, 3000);
现在你有了真正的 javascript 代码(不是字符串),它在没有使用 eval() 的情况下被评估,并且由于闭包,你可以完全访问封闭函数的局部变量和参数,这给了你访问whichImage(一个参数)和width(一个局部变量),这样你的代码就可以工作了。
这是第 14 条原因,您应该始终使用真正的 javascript 函数引用或匿名函数声明,而不是将字符串传递给 setTimeout()。
【解决方案3】:
您需要将代码块包装在一个匿名函数中,例如:
setTimeout(function () {
whichImage.width=width;
}, 3000);
【解决方案4】:
试试:
setTimeout(function() {
whichImage.width=width;
},3000);
【解决方案5】:
你不需要为此使用 eval
setTimeout(function() { whichImage.width=width; } ,3000);
这是你的功能
function resizeImageFunction(whichImage){
var halfwidth = Math.round(width/2);
whichImage.width=halfwidth;
setTimeout(function() { whichImage.width=width; } ,3000);
}