gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 03:19:59 24 4
gpt4 key购买 nike

我尝试创建一个 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,这意味着它在第二次超时时不可用。你可能 want to read about closure & scoping在 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
}

关于Javascript 在延迟后打开一个窗口,然后在另一个延迟后关闭它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73303924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com