You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Window opener与onclick结合异常:需实现每隔5秒逐个打开窗口

问题分析

你的代码存在两个核心问题:

  1. 所有setTimeout都设置了相同的5000毫秒延迟,导致三个链接会在点击后同时触发,而非每隔5秒逐个执行。
  2. openLink函数复用同一个窗口对象,每次调用都会覆盖当前窗口的URL,无法实现有序的跳转或新窗口打开逻辑。
解决方案

根据你的需求,分两种场景提供实现代码:

场景1:在同一个窗口中每隔5秒依次跳转链接

通过递增延迟时间,或使用递归链式调用确保每个操作间隔5秒执行:

方式1:手动设置递增延迟

let newWindow = null;

function openLink(link){
  if(newWindow === null){
    newWindow = window.open(link, '_blank');
  } else {
    newWindow.location.href = link;
  }
}

flink.onclick = function() {    
  openLink('https://www.baidu.com');
  setTimeout(() => openLink('https://www.reddit.com'), 5000);
  setTimeout(() => openLink('https://www.youtube.com'), 10000);
  setTimeout(() => openLink('https://www.stackoverflow.com'), 15000);
}

方式2:递归链式调用(适合多链接场景)

let newWindow = null;
const links = [
  'https://www.baidu.com',
  'https://www.reddit.com',
  'https://www.youtube.com',
  'https://www.stackoverflow.com'
];

function openLink(link){
  if(newWindow === null){
    newWindow = window.open(link, '_blank');
  } else {
    newWindow.location.href = link;
  }
}

function openSequentially(index = 0) {
  if (index >= links.length) return;
  openLink(links[index]);
  setTimeout(() => openSequentially(index + 1), 5000);
}

flink.onclick = function() {    
  openSequentially();
}

场景2:每隔5秒打开一个新窗口

修改openLink函数取消窗口复用,同时用递归确保间隔执行:

const links = [
  'https://www.baidu.com',
  'https://www.reddit.com',
  'https://www.youtube.com',
  'https://www.stackoverflow.com'
];

function openLink(link){
  window.open(link, '_blank');
}

function openSequentially(index = 0) {
  if (index >= links.length) return;
  openLink(links[index]);
  setTimeout(() => openSequentially(index + 1), 5000);
}

flink.onclick = function() {    
  openSequentially();
}
注意事项

部分浏览器的弹窗拦截机制可能会阻止后续的自动弹窗,建议在页面中提示用户允许弹窗权限,以确保功能正常运行。

内容的提问来源于stack exchange,提问作者K.Mughal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 07:55:27