Open links, one after another

不羁的心 提交于 2019-12-02 14:01:11

问题


I'm making a website where I'm opening a new window every 30 seconds. I got it to open the new windows properly, but I would like it to close the last window opened before opening the new one, so only one window is open at a time. How would I do this? Here's my code so far:

<script type="text/javascript">
function open_win() {
    window.open("http://www.wol.com");
    setTimeout(window.open('http://www.bol.com'),35000);
    setTimeout(window.open('http://lol.com'),70000);
    setTimeout(window.open('http://col.com'),105000);

}
</script>

回答1:


You can close a window opened by calling window.close on window.open's return value. So:

<script type="text/javascript">
function open_win() {
    var wol,bol,lol;
    wol=window.open("http://www.wol.com");
    setTimeout(function(){window.close(wol);bol=window.open('http://www.bol.com')},35000);
    setTimeout(function(){window.close(bol);lol=window.open('http://lol.com')},70000);
    setTimeout(function(){window.close(lol);window.open('http://col.com')},105000);

}
</script>



回答2:


Here a small interval loop for calling urls. Feel free to add an array for different URLS.

<script type="text/javascript">
    var lastWindow = "";
    setInterval(function(){
        if(lastWindow != ""){ lastWindow.close(); }
        lastWindow = window.open("url");
    }, 30000);
</script>



回答3:


You can use a string array to store all of the links, and then iterate through that loop calling open and close after 30 seconds. Using a loop and abstracting open/close allows you to have as many links as you'd like.

var linkArray = ['http://www.wol.com', 'http://www.bol.com', 'http://lol.com', ['http://col.com']

function openWin(link) { 
    var currentWindow = window.open(link);
    setTimeout(currentWindow.close(), 30000);
}

function runLinks() {
    for(var i = 0; i< linkArray.length; i++) {
          openWin(linkArray[i]);
    }
}


来源:https://stackoverflow.com/questions/28267905/open-links-one-after-another

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