Javascript在延迟后打开一个窗口,然后在另一个延迟后关闭它



我尝试创建一个JavaScript函数,当用户单击按钮时,在一小段时间后打开一个新选项卡,然后等待一秒钟并关闭它。

目前,我的代码如下所示:

var btn = document.getElementById("myLink");
btn.onclick = function() {
setTimeout(function() {
var win = window.open(
"http://www.stackoverflow.com", 
"The new Link")
},500);
setTimeout(function(){
win.close();
if (win.closed) {
clearInterval(timer);
winClosed();
alert("'The new Link' window closed !");
}
}, 2500);
}

但是第二个setTimeout函数不会执行。当我删除两个setTimeout函数中的一个时,另一个工作正常,但我需要运行这两个函数。

编辑:更改了超时值以考虑@lk77注释。

您的代码中有 2 个问题。

  1. 您正在初始化变量win在第一次超时,这意味着它在第二次超时中将不可用。你可能想阅读javascript中的闭包和范围。
  2. 您的第一次超时的延迟为1500毫秒,第二次超时500,这意味着第二次超时在第一次超时之前触发。

这应该有效:

var btn = document.getElementById("myLink");
btn.onclick = function() {
var win = null; // initialize here so it is available in both timeouts
setTimeout(function() {
win = window.open( // set the value here
"http://www.stackoverflow.com", 
"The new Link")
},500); // this should fire first
setTimeout(function(){
win.close();
if (win.closed) {
clearInterval(timer);
winClosed();
alert("'The new Link' window closed !");
}
}, 1500); // this should fire second
}

第二个setTimout的回调将像你一样在第一个回调之前执行。解决此问题的方法是在第一个setTimeout中添加第二个,如下所示:

let btn = document.getElementById("myLink");
btn.onclick = function () {
setTimeout(function () {
let win = window.open("http://www.stackoverflow.com", "The new Link");
let timer = setTimeout(function () {
win.close();
if (win.closed) {
clearInterval(timer);
//winClosed();
//alert("'The new Link' window closed !");
}
}, 1000);
}, 500);
};

相关内容

最新更新