0

I'm trying to open new URLs with different timing but it does not work

<script type="text/javascript">
setTimeout(function() {window.location="http://google.com";}, 2000);
setTimeout(function() {window.location="http://youtube.com";}, 5000);
</script>

This scrpit can only open the first link. Any ideas ?

maco45
  • 3
  • 1
  • 4
    When you navigate to the first link you lost all scripts from the initial page. So listeners/timeouts/intervals are trashed. – bel3atar May 17 '21 at 14:18
  • 1
    use `window.open` with `_blank` as second parameter as `setTimeout(function () { window.open("http://google.com", '_blank'); }, 2000);` – DecPK May 17 '21 at 14:22
  • [javascript window.location in new tab](https://stackoverflow.com/questions/7554108) – adiga May 17 '21 at 14:22

3 Answers3

0

When the first line is executed then you are redirected to http://google.com. At this point your page has changed and the script you have written for youtube.com won't be on this page as this is a new page.

heysujal
  • 118
  • 7
0

window.location will set the path of the browser window you are executing this script from. In this case, you are navigating to http://google.com, and then your second timeout will never execute.

In order to fix this, you could try opening the URLs in a different tab or window with window.open and the _blank parameter.

<script type="text/javascript">
setTimeout(function() {window.open("http://google.com", "_blank")}, 2000);
setTimeout(function() {window.open("http://youtube.com", "_blank")}, 5000);
</script>

circadian
  • 118
  • 1
  • 6
0

You can (spawn) open the links in a new tab.

Note: The tabs will not open in this embedded snippet, because the sandbox does not allow popups.

// Adapted from: https://stackoverflow.com/a/57216987/1762224
const openTab = (href, target = '_blank') => {
  const link = Object.assign(document.createElement('a'), { href, target });
  document.body.append(link);
  link.click();
  link.remove();
  console.log(`Opening: ${href}`);
}

setTimeout(() => openTab('http://google.com'), 2000);
setTimeout(() => openTab('http://youtube.com'), 5000);
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132