-1

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?

JayJona
  • 469
  • 1
  • 16
  • 41
  • My guess is a scope problem. There's only one `win` variable, so all of the timeouts will only ever refer to the last window. Move the `let` declaration into the loop. – David Dec 22 '22 at 14:01
  • @mplungjan no errors on the console, when I console log the window I see correctly the object – JayJona Dec 22 '22 at 14:01
  • Put the loop inside the `setTimeout()` callback and close each window within the loop. – Randy Casburn Dec 22 '22 at 14:03
  • @RandyCasburn this does not work, also when I console log the window now I see 'global {window: null, self: null, location: {…}, closed: true, frames: null, …}' – JayJona Dec 22 '22 at 14:12
  • @David tried but did not work – JayJona Dec 22 '22 at 14:14
  • 1
    @JayJona - it does work - here is a working example: https://jsbin.com/kuhocoweri/edit?js,console – Randy Casburn Dec 22 '22 at 14:24
  • @JayJona: [Works for me](https://jsfiddle.net/xq6mbjhc/). Can you provide a runnable [mcve] which demonstrates the problem? – David Dec 22 '22 at 14:27
  • 1
    why use two loops? Just create the timeout when you open it `for(let i=0; i { if(!openWindow.closed) openWindow.close(); }, 2000); }` – epascarello Dec 22 '22 at 14:50

1 Answers1

1

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()
mplungjan
  • 169,008
  • 28
  • 173
  • 236