setTimeout()获取窗口,在setTimeout激活之前显示其他脚本函数

setTimeout() get window to display other script functions before setTimeout activates

本文关键字:setTimeout 显示 其他 函数 脚本 获取 窗口 激活      更新时间:2023-09-26

我相信这是一个被问过很多次的普遍问题,但无法找到解决方案。

我有javascript使用setTimeout()函数关闭一个弹出窗口,我创建了一段时间后。

问题:如果我在创建弹出窗口的同一脚本中调用setTimeout()函数,则弹出窗口不显示窗口的内容,而是整个功能像单个脚本一样,窗口关闭。这就像你需要以某种方式中断脚本,让它在执行setTimeout之前解析脚本的每个部分。

有人知道为什么或有一个解决方案吗?

<script>
var w;
function closeWindow(){ setTimeout(w.close();, 10000);}
function createWindow(){
//create the popup window.
w=window.open("","",'width=200,height=100');
// put something into the popup window
try{w.document.write('<html><head></head><body><p>the w window</p></body>  
<html>')}catch(err){
//handle error here
}
closeWindow();
//closes the createWindow() function
}
</script>

我玩了你的脚本。以下已经过测试并正常运行:

var w;
function closeWindow(){ setTimeout("w.close();", 10000);}
function createWindow(){
//create the popup window.
w=window.open("","",'width=200,height=100');
// put something into the popup window
try{w.document.write('<html><head></head><body><p>the w window</p></body> <html>')}catch(err){
//handle error here
}
closeWindow();
//closes the createWindow() function
}

如果我没记错的话,需要在setTimeout函数的code参数周围加引号,否则你将传递代码的返回值作为setTimeout的参数,而不是它运行所需的代码。

使用setTimeout的正确语法:

setTimeout(function() {
    w.close();
}, 10000);

函数获取字符串字面值,然后计算,或者执行命令的更好选择是一个函数:它可以是现有函数的名称(参见下面的示例),也可以像上面那样,匿名函数。

以不同方式使用该函数的示例:

window.setTimeout(closeWindow, 10000);

功能为:

function closeWindow() {
    w.close();
}

尝试如下:

setTimeout(w.close, 10000);