Javascript setTimeout() 和窗口函数
以下 JavaScript 代码在 Chrome 中运行,并导致“背景”窗口的大小调整为我的规格:
var background;
function play () {
var w = screen.width;
var h = screen.height;
if( !background || background.closed ) background = window.open("background.html", "It's a pop-up!", "top="+ 100 +",left="+ 770 +",width="+ w/3 +",height="+ h/3 +",location=no,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=no");
background.resizeTo(w,724);
}
但是,当我尝试延迟调整大小功能时,代码会中断。为什么调用 setTimeout("background.resizeTo(w,724)",10000)
没有可见结果?
The following JavaScript code runs in chrome, and results in the "background" window being resized to the my specifications:
var background;
function play () {
var w = screen.width;
var h = screen.height;
if( !background || background.closed ) background = window.open("background.html", "It's a pop-up!", "top="+ 100 +",left="+ 770 +",width="+ w/3 +",height="+ h/3 +",location=no,menubar=no,scrollbars=no,status=no,toolbar=no,resizable=no");
background.resizeTo(w,724);
}
When I try to delay the resize function, however, the code breaks. Why does calling setTimeout("background.resizeTo(w,724)",10000)
have no visible result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将其更改为
您应该传递一个函数。这是正确的解决方案,在使用
setTimeout()
或setInterval()
时,不要依赖将字符串作为“函数”传递,它会更慢,因为它必须进行评估,这是不正确的。此外,您可能会遇到范围问题(如您的示例中所示)。仅当
background
和w
都是全局时,您的代码才有效。我们不知道background
,但w
绝对只是play
的本地内容。传递一个关闭这些变量的函数(闭包)而不是字符串,可以解决这个问题。有关它的更多信息: https://developer.mozilla.org/en/DOM /window.setTimeout#语法
Change it to
You should pass a function. This is the proper solution, don't ever rely on passing a string as a 'function' when using
setTimeout()
orsetInterval()
, it's slower because it has to be evaluated and it just isn't right.Furthermore you may have problems with the scope (like in your example). Your code would only work if both,
background
andw
are global. We don't know aboutbackground
, butw
is definitely only local toplay
. Passing a function which closes over those variables (a closure) instead of a string, solves this problem.For more info about it: https://developer.mozilla.org/en/DOM/window.setTimeout#Syntax
因为整个语句基本上已经被评估了,w 已经没有任何意义了。
试试这个:
Because the entire statement is basically eval'd and w has no meaning anymore.
try this: