Javascript 尝试多次使用超时函数

Javascript 尝试多次使用超时函数,javascript,html,Javascript,Html,我尝试多次使用超时功能,但它只运行一次。我试图在6秒后获得第二个URL 3秒后的第一个,工作正常。也尝试了if-else语句,但没有效果 <!doctype html> <html> <body> <p>You will be redirected in 3 seconds</p> <script> var time = setTimeout(function () {

我尝试多次使用超时功能,但它只运行一次。我试图在6秒后获得第二个URL

3秒后的第一个,工作正常。也尝试了if-else语句,但没有效果

<!doctype html>
<html>
<body>
    <p>You will be redirected in 3 seconds</p>
    <script>
        var time = setTimeout(function () {
            window.location = 'http://example.com'
        }, 3000);

        var one = setTimeout(function () {
            window.location = 'http://google.com'
        }, 6000);
    </script>
</body>
</html>

您将在3秒钟内被重定向

变量时间=设置超时(函数(){ window.location=http://example.com' }, 3000); var one=setTimeout(函数(){ window.location=http://google.com' }, 6000);
JavaScript(在此上下文中)在网页内运行

离开页面时,会破坏JavaScript运行的环境


您不能在导航到其他页面后三(或任何其他时间)秒运行JavaScript函数。

正如@Quentin所提到的,您无法使其与现有代码一起工作

按照您在评论中的要求,请使用IFRAME尝试以下内容

<!doctype html>
<html>
<body>
    <p>You will be redirected in 3 seconds</p>
    <!-- use your CSS skills to adjust iframe on the page -->
    <!-- You can also decide if you want to hide iframe intially and show it on first load -->
    <iframe id="iframe_window" src='about:blank' style="height:100%;width:100%;"></iframe>
    <script>
        var time = setTimeout(function () {
            document.getElementById['iframe_window'].src = 'http://example.com';

        }, 3000);

        var one = setTimeout(function () {
           document.getElementById['iframe_window'].src = 'http://google.com';
        }, 6000);
    </script>
</body>
</html>

您将在3秒钟内被重定向

变量时间=设置超时(函数(){ document.getElementById['iframe\u window'].src='10〕http://example.com'; }, 3000); var one=setTimeout(函数(){ document.getElementById['iframe\u window'].src='10〕http://google.com'; }, 6000);
您可以这样做(在
窗口中使用
“\u blank”
。打开
而不是
窗口。位置


您将在3秒钟内被重定向

setTimeout(函数(){ 打开窗户http://www.example.com","空白",; }, 3000); setTimeout(函数(){ 打开窗户http://google.com","空白",; }, 6000);

您可以使用
window.location=”“
指定窗口的位置。当第一次执行
window.location
时,它将丢失第一个代码并重定向到
www.example.com
页面。现在,如果你想实现这一点,那么你必须在
www.example.com
中放置另一个
窗口。位置

3秒钟后,你将被重定向到example.com,因此当前的js执行将被新加载的页面所取代。尝试在单独的选项卡中打开它。我不知道你的确切目的是什么提供这种类型的功能。正如Quentin提到的,您不能像这样实现它,但是如果您仍然想要使用它,并且没有任何安全绑定,您可以使用IFRAME来完成。如果您需要使用IFRAME的代码,请告诉我您是否拥有/控制要重定向到的页面?K D,请共享IFRAME代码。我们可以增加时间间隔,就像10秒后加载第一页,20秒后加载下一页一样。谢谢Emil:不,我不拥有这些页面。如果将一个页面的时间间隔从3秒增加到10秒,我们可以实现吗?不。JS运行的页面在你离开页面时被破坏,但在7秒后仍然被破坏。谢谢Shubham。我试着关闭账单。比如,如果谷歌标签打开,那么示例标签关闭。我正在尝试使用window.close(),但它不起作用。
<!doctype html>
<html>
<body>
    <p>You will be redirected in 3 seconds</p>
    <script>
        setTimeout(function () {
             window.open('http://www.example.com','_blank');
        }, 3000);

setTimeout(function () {
    window.open('http://google.com','_blank');
        }, 6000);

    </script>
</body>
</html>