Search code examples
javascriptloopssettimeoutwindow.open

In the browser console, open the url in a new tab with a delay


I have an array of URLs and I want to open all these URLs one by one in the new tab with the specified delay. I have tried the below method, but it opens all URLs in a one-shot after a delay of 2 seconds. Please suggest the code changes.


items = ["a.com", "b.com", "c.com", "d.com"]

items.forEach((url, index) => {
    if (index <= 49) {
        setTimeout(() => {  window.open(url, "_blank"); }, 2000);
    }
})

Solution

  • Use async function for that.

    Sample Implementation.

    items = ["a.com", "b.com", "c.com", "d.com"];
    
    function resolveAfter2Seconds(index) {
      return new Promise(resolve => {
        setTimeout(() => {
          window.open(items[index], "_blank")
          resolve('resolved');
        }, 2000);
      });
    }
    
    async function asyncCall() {
      console.log('calling');
      let index = 0;
      while (index < items.length) {
        const result = await resolveAfter2Seconds(index);
        console.log(result);
        // expected output: "resolved"
        index++;
      }
    }
    
    asyncCall();