问题描述
我有一组 URL,需要循环访问并在新窗口中打开.但是,我需要能够在每个窗口的打开和关闭之间设置超时.换句话说,窗口应该只在设定的时间间隔内保持打开状态,然后移动到数组中的下一个 URL.
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;
}
)();
想法?
推荐答案
您的 for 循环
一次有效地运行所有内容,因此您的代码一次打开所有窗口,然后关闭超时全部在 2 秒后启动(全部同时启动).
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.
这是一种方法:
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 数组并打开,然后以定义的间隔关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!