Search code examples
javascriptsettimeoutwindow.open

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


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?


Solution

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

    EDIT: 10 Years later (2024), it's worth noting that in order to open a new window/tab via JavaScript in any modern browser, the script has to be triggered by a user interaction. A method like this one, will not actually open the window/tab. Even if this loop were called in a click event handler, only the first iteration would work as subsequent calls to window.open would need to run in new click handlers.