问题
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