在浏览器控制台中,延迟在新选项卡中打开 url

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

我有一组 URL,我想在新选项卡中以指定的延迟时间一个一个地打开所有这些 URL。我试过下面的方法,但它会在延迟 2 秒后一次性打开所有 URL。请建议代码更改。


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

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

为此使用 async function

实施示例。

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();