Javascript: Iterate through array of URLs and open, then close at defined interval

做~自己de王妃 提交于 2020-01-05 08:21:48

问题


I have an array of URLs that I need to loop through and open in a new window. However, I need to be able to set a timeout between each window's open and close. In other words, the window should only stay open for a set interval, then move on to the next URL in the array.

The following code opens the windows, but only closes the first one.

        (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;
        }
        )();

Ideas?


回答1:


Your for loop runs everything effectively all at once, so your code is opening all the windows at once, and then your close timeouts all launch 2 seconds later (all at the same time).

You need to have a timeout between each iteration of the array.

Here would be a way to do this:

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();


来源:https://stackoverflow.com/questions/23701987/javascript-iterate-through-array-of-urls-and-open-then-close-at-defined-interv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!