javascript 使用 setInterval 打开和关闭多个 url

标签 javascript setinterval

我试图在 javascript 中打开多个 url 几秒钟并自动关闭它们。我没有编程背景知识,只有一点点php。我这样做是为了演示一个项目。

我有一个包含一些网址的数组。

var allURL = ["http://google.com", "http://yahoo.com", "http://msn.com"];

现在我想在新窗口/选项卡中一一打开所有网址 10 秒并自动关闭。所以http://google.com打开 10 秒并自动关闭,然后 http://yahoo.com打开。与数组中的所有 url 类似。

您能否指导我如何使用 setInterval 或任何其他方式来实现这一点。

最佳答案

var allURL = ["http://google.com","http://yahoo.com","http://msn.com"];

function showUrl(index) {
    index = index || 0;

    // are there any urls to show?
    // is the given index valid?
    if (allURL.length === 0 || index < 0 || index >= allURL.length) {
        return;
    }

    // open the url
    var popup = window.open(allURL[index]);

    // set a timer which closes the popup after 10 seconds and opens the next url by calling 'showUrl' with the next index
    setTimeout(function() {
        popup.close();
        showUrl(index + 1);
    }, 10000);
}

// To start the "diashow" call 'showUrl' without an index or if you want to start at a pre-defined url with the corresponding index
showUrl();    // starts with the first url

关于javascript 使用 setInterval 打开和关闭多个 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10751360/

相关文章:

JavaScript 动画的持续时间不准确

javascript - 即使 previos 尚未完成其工作,是否会触发传递给 setInterval 的回调

javascript - 使用 jQuery 执行动态传递的函数调用

javascript - 在 for 循环中编写代码

javascript - 如何在 Accordion 中隐藏/可见元素

javascript - 是否有可能将 "setInterval"设置得太快?

javascript - setInterval 函数调用的问题

Javascript setInterval 未运行

javascript - Chrome 扩展程序 : Is it possible to create a TCP/Websocket based server on a folder?

javascript - 图像上传、调整大小和编码为 base64 导致 Chrome 在移动设备上崩溃