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

标签 javascript settimeout window.open

我有一个 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;
        }
        )();

想法?

最佳答案

您的 for 循环 一次有效地运行所有内容,因此您的代码会同时打开所有窗口,然后您的关闭超时将在 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();

关于Javascript:遍历 URL 数组并打开,然后按定义的时间间隔关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23701987/

相关文章:

jquery - 如何给onClick window.open添加5秒延迟?

javascript - 如何加载远程数据到select2并按标题搜索

java - 是否可以在javascript中反序列化java对象

javascript - 什么是序言指令?

javascript - 即使检查 onload 事件 javascript,iframe 内容也不会出现在屏幕上

Javascript:将类/对象引用设置为 NULL,内存中的子对象/类会发生什么?

javascript - 如何向 map 添加自定义上下文菜单

javascript - 如何在表单提交前等待3秒?

javascript - $(document).ready() 立即触发 window.open() 上下文

javascript - Window.open使页面变成弹出 block