javascriptpopupsetintervalonloadclearinterval

javascript window.open not following setInterval parameters?


I have a very oddly specific project which requires a number of photos to be opened in multiple window popups. (I understand the usability of this, please bypass that for the moment.)

I am running the following script on body load, which works somewhat so far:

// Popup window code
function runPopups() {
  popupWin1 = setInterval(
    function() {
      window.open('assets/pic1.jpg', '_blank', 'width=490,height=300,left=-1000,top=-1000')
    }, 3000);
  //clearInterval(popupWin1);

  popupWin2 = setInterval(
    function() {
      window.open('assets/pic2.jpg', '_blank', 'width=600,height=500,left=0,top=0')
    }, 3000);
  //clearInterval(popupWin2);
}

It actually seems to sort of load them once but then keeps looping back through. When I add the clearInterval parameter, it breaks the script altogether. I'm so close but not sure what I'm doing wrong as javascript is not my main understanding. I feel like I'm either missing a loop somehow or maybe I need to put it into a whole different function?

Ideally, I want each photo to pop up in a random spot on the screen, with a varied delayed time - bonus if each one can be faster and faster. I will have about 10-20 pics to pop up. Help is greatly appreciated!


Solution

  • You want to use a for loop with setTimeout to schedule each popup individually. If each popup has a different name and parameters, you can store that in an array and loop through it with a for loop.

    const popups = [
      {
        url: 'assets/pic1.jpg',
        params: 'width=490,height=300,left=-1000,top=-1000',
      },
      {
        url: 'assets/pic2.jpg',
        params: 'width=600,height=500,left=0,top=0',
      },
      // Add the rest here
    ];
    
    function runPopups() {
      for (let i = 0; i < popups.length; i++) {
        setTimeout(
          () => window.open(popups[i].url, '_blank', popups[i].params),
          (i + 1) * 3000
        );
      }
    }
    

    Example: https://stackblitz.com/edit/typescript-2rgp5n?file=index.ts

    You're scheduling the first one to popup after 3 seconds, the second after 6 seconds, the third after 9 seconds, etc. If you want the first to appear immediately just remove the + 1.