javascript一段时间后关闭打开的窗口



我正在制作一个javascript脚本,从网页打开其他网页的列表。我能够打开所有的页面,但然后我需要在一些时间后关闭这些网页,但似乎setTimeout不起作用。下面是代码

function OpenAllLinks() {

const array = Array.from(mySet1); //here I get an array of urls as string
let opened_pages = [];
let openWindow = null;
for(i=0; i<array.length; i++){
openWindow = window.open(array[i], '_blank');
opened_pages.push(openWindow);
}
let win = null;
for(i=0; i<opened_pages.length; i++){
win = opened_pages[i];
console.log(win);
try {
setTimeout(function(){win.close()},2000); // after two seconds the page are still open
} catch (error) {
console.log(error);
}
}
}

那么我如何在一段时间后关闭网页列表呢?

不要循环settimeout。而是像这样迭代地调用它:

const mySet1 = new Set();
mySet1.add("url1");
mySet1.add("url2");
mySet1.add("url3");
let opened_pages = [];
const array = [...mySet1];
let cnt = 0;
const openAllLinks = () => {
if (cnt >= array.length) { // done
cnt = 0;
setTimeout(closeAllLinks, 2000); // close the first after 2 seconds
return;
}
opened_pages.push(window.open(array[cnt], '_blank'));
cnt++;
setTimeout(openAllLinks, 10); // give the interface a breather
};
const closeAllLinks = () => {
if (cnt >= opened_pages.length) return; // done
try {
opened_pages[cnt].close();
} catch (error) {
console.log(error);
return; // stop
}
cnt++;
setTimeout(closeAllLinks, 10); // give the interface a breather
};
openAllLinks()

最新更新