JavaScript中setTimeout无法延迟关闭window.open打开的窗口求助
问题分析与解决方案
你的代码里弹窗被立即关闭的原因很明确:你给setTimeout传的不是函数引用,而是直接执行了handle.close()。
当你写setTimeout(handle.close(), 3000)时,代码会立刻调用handle.close()关闭窗口,然后把这个方法的返回值(undefined)传给setTimeout,完全达不到延迟执行的效果。
修正后的代码
有两种常用的修正方式:
方式一:使用箭头函数包裹
let handle = window.open(link, '_blank', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left) setTimeout(() => handle.close(), 3000);
方式二:使用bind绑定上下文
let handle = window.open(link, '_blank', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left) setTimeout(handle.close.bind(handle), 3000);
说明
- 方式一通过箭头函数把
handle.close()包装成一个待执行的函数,确保3秒后才触发关闭操作,同时保留了正确的窗口对象引用。 - 方式二用
bind(handle)将close方法的上下文绑定到弹窗窗口对象,避免this指向错误,同时传递的是函数本身而非执行结果。
内容的提问来源于stack exchange,提问作者BlurredVision
相关产品推荐
相关产品推荐

