How to update the same browser page with new URLs with a specific delay using Javascript?

一世执手 提交于 2020-01-03 02:26:08

问题


I want to open 10 webpages one after another, in the same browser window and with some specific delay.

e.g. I want

  1. open "www.Anywebsite.com"
  2. Delay 5 seconds
  3. In the same page open a new "www.Anywebsite.com"

I am trying to do something like this

<!DOCTYPE html>
<html>
<body>

<script>
var myVar=setInterval(function(){myTimer()},1000);
var condOpen = 0;
function myTimer()

{
if (condOpen == 0)
{
window.open("http://www.tut.fi","_self"); 
condOpen = condOpen + 1;
}
else if(condOpen == 1)
{
window.open("www.w3schools.com","_self"); 
}
}
</script>

</body>
</html>

The problem is it opens only the first page, and as I read about "setInterval", it must execute the function specified after some delay. Please help me in this, I have no prior experience with JavaScript but this is needed for a particular task I am doing.


回答1:


Your code is failing because when you call window.open() with the _self parameter, it's just like doing window.location = "http://www.example.com/";. This replaces your page with the new page you're loading. All JavaScript on your page is killed, including any timers.

You can do something like what you're trying to do here, but you would need to use a different target window name in the window.open() call. You can make up any arbitrary name here; just don't begin the name with _ to avoid the special names like _self.

Unfortunately, you will run afoul of popup blockers if you do this. In order to get past the popup blockers, what you need to do is have the first window.open() be triggered directly by a user action, e.g. by clicking a button. After that you can use the timer to change URLs in the window you've opened.

Also you will get tired of writing if statements when you want to add more URLs to your list. You can use an array of URLs to simplify the code.

And finally, it would be a really good idea to indent your JavaScript code to show its structure. Putting it all against the left margin makes it hard to follow.

Putting those together:

<!DOCTYPE html>

<html>
<head>
    <title>Window Loop Test</title>
</head>

<body>

<button onclick="start()">Start</button>

<script>
    var targets = [
        'http://www.stackoverflow.com/',
        'https://developer.mozilla.org/en-US/',
        'http://www.w3fools.com/'
    ];

    var iTarget;

    function nextTarget(){
        window.open( targets[iTarget], 'target' );
        if( ++iTarget >= targets.length ) {
            iTarget = 0;
        }
    }

    function start() {
        iTarget = 0;
        nextTarget();
        setInterval( nextTarget, 5000 );
    }
</script>


</body>
</html>

And here is a fiddle to test.



来源:https://stackoverflow.com/questions/17611204/how-to-update-the-same-browser-page-with-new-urls-with-a-specific-delay-using-ja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!