Javascript:遍历 URL 数组并打开,然后按定义的时间间隔关闭

问题描述 投票:0回答:1

我有一个 URL 数组,需要循环遍历并在新窗口中打开。但是,我需要能够在每个窗口的打开和关闭之间设置超时。换句话说,窗口应该只在设定的时间间隔内保持打开状态,然后移至数组中的下一个 URL。

以下代码打开窗口,但仅关闭第一个窗口。

        (function X() {
            document.getElementById("target").onclick = function () {

                var urlList = ['http://www.google.com', 'http://www.msn.com', 'http://www.yahoo.com'];
                var wnd;

                for (var i = 0; i < urlList.length; i++) {
                   wnd = window.open(urlList[i], '', '');

                    setTimeout(function () {
                        wnd.close();
                    }, 2000);

                }

            };
            return true;
        }
        )();

想法?

javascript settimeout window.open
1个回答
2
投票

您的

for loop
一次有效地运行所有内容,因此您的代码会立即打开所有窗口,然后您的关闭超时将在 2 秒后全部启动(全部同时)。

数组的每次迭代之间需要有一个超时。

这是一种方法:

var urlList = ['http://www.google.com', 'http://www.msn.com', 'http://www.yahoo.com'];
var wnd;
var curIndex = 0; // a var to hold the current index of the current url

function openWindow(){
    wnd = window.open(urlList[curIndex], '', '');
    setTimeout(function () {
         wnd.close(); //close current window
         curIndex++; //increment the index
         if(curIndex < urlList.length) openWindow(); //open the next window if the array isn't at the end
    }, 2000);
}

openWindow();

编辑: 10 年后(2024 年),值得注意的是,为了在任何现代浏览器中通过 JavaScript 打开新窗口/选项卡,脚本必须由用户交互触发。这是一种很可能会失败的方法。即使在单击事件处理程序中调用此循环,也只有第一次迭代才能工作,因为对

window.open
的后续调用需要在新的单击处理程序中运行。

© www.soinside.com 2019 - 2024. All rights reserved.