Javascript:迭代URL数组并按定义的间隔打开,然后关闭
我有一个URL数组,需要在新窗口中循环打开。但是,我需要能够在每个窗口的打开和关闭之间设置一个超时。换句话说,窗口应该只在设置的时间间隔内保持打开状态,然后移动到数组中的下一个URL 以下代码打开窗口,但仅关闭第一个窗口Javascript:迭代URL数组并按定义的间隔打开,然后关闭,javascript,settimeout,window.open,Javascript,Settimeout,Window.open,我有一个URL数组,需要在新窗口中循环打开。但是,我需要能够在每个窗口的打开和关闭之间设置一个超时。换句话说,窗口应该只在设置的时间间隔内保持打开状态,然后移动到数组中的下一个URL 以下代码打开窗口,但仅关闭第一个窗口 (function X() { document.getElementById("target").onclick = function () { var urlList = ['http://www.g
(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;
}
)();
(函数X(){
document.getElementById(“目标”).onclick=function(){
var urlist=['http://www.google.com', 'http://www.msn.com', 'http://www.yahoo.com'];
var-wnd;
对于(var i=0;i
想法?您的
for loop
一次有效地运行所有内容,因此您的代码一次打开所有窗口,然后您的关闭超时都会在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();
var urlist=['http://www.google.com', 'http://www.msn.com', 'http://www.yahoo.com'];
var-wnd;
var curIndex=0;//保存当前url的当前索引的变量
函数openWindow(){
wnd=window.open(urlist[curIndex],'','');
setTimeout(函数(){
wnd.close();//关闭当前窗口
curIndex++;//增加索引
if(curIndex
这将仅打开和关闭第一个窗口。数组中的其他URL未打开。可能是因为我在openWIndow()
中有一个输入错误,请将“I”改为小写,它应该可以工作。这样做了。谢谢