Search code examples
javascripttimeoutsettimeout

javascript close opened windows after some time


I am making a script in javascript that from a webpage opens a list of other webpages. I'm able to open all the pages but then I need to close these webpages after some times but appear that setTimeout does not work. Here is the code

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);
        }
    }
}

So how can I close a list of webpages after some time?


Solution

  • Don't loop setTimeouts. Instead call it iteratively like here:

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