0

I want to create a pop window and open a list of URLs in the browser. So when the first page loads in the pop up window, Wait for the page to load then open the next page... Go through the list of urls. To wait for the page to load, I use setTimeout. But I can't seem to make my code work, because of the for loop and the setTimeout. The window skips directlt to the last url in the list. Is there any other way I can make it work? Thank you,

Here's my code:

// exammple of list urls
var my_list = ['https://www.youtube.com/watch?v=77kOn5NZBHw',
  'https://www.youtube.com/watch?v=1IRo21UhvZg',
  'https://www.youtube.com/watch?v=yRJxz0NicgI'
]

// open a new pop up window
var response = window.open(my_list[0], 'new', true);

for (let i = 0; i < my_list.length; i++) {
    setTimeout(function() {
    console.log(response.location.href);
    response.location = my_list[i];
  }, 3000)

};
picoRadia
  • 11
  • 3
  • You can obviously format your code any way you like for your own purposes, but when asking people for help, it's only courteous to take the time to format the code in a readable, consistent way. – T.J. Crowder Apr 22 '22 at 08:07
  • You've only a single window of which you're changing the location. – Teemu Apr 22 '22 at 08:07
  • You could use the `onload` event of `window` instead of a timeout. Depending on the URL of course. – Lain Apr 22 '22 at 08:24
  • @T.J.Crowder Sorry I wrote that code in the console's browser not in an editor. I'll fix it! – picoRadia Apr 22 '22 at 09:40
  • @Lain I see what you mean with using onload, but i genuinely want to wait 3000 for example after the page is loaded. Ths problem with thesetTimeout inside the for loop is that it executes the for loop then setTimeout. Thus fetching the last index returned by the for loop. – picoRadia Apr 22 '22 at 11:03
  • **Thus fetching the last index returned by the for loop.** If that is your main issue you can [`bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) the `my_list[i]` like `setTimeout(function(link){console.log(link)}.bind(this, my_list[i]), 3000)`. – Lain Apr 22 '22 at 11:47
  • @picoRadia The current code you have works as it is. Only that `setTimeout` doesn't block, the callback is executed three times within a millisecond after the delay of 3 secs has expired, and you can see only the last loaded page in the pop-up. Give the delay like `i * 3000` to load the pages 3 secs after each other. It's also notable, that there's only a single window opened. If you want to open three separate pop-ups, move the `window.open()` line to the callback, and use `i` to give a different string as the windowName argument. – Teemu Apr 23 '22 at 09:55
  • @Teemu Thank you so much! Adding i * 3000 gives me exactly the behaviour I wanted. How can I please close this qestion? – picoRadia Apr 25 '22 at 07:54

0 Answers0