【问题标题】:Open and close websites with intervals js使用间隔js打开和关闭网站
【发布时间】:2015-02-23 23:51:12
【问题描述】:

我需要构建一个程序,打开一个网站,等待大约 5 秒,然后关闭网站并打开另一个网站,它需要循环大约 5 次。网站的 URL 会像我的代码一样发生变化。我只是不知道如何使用整个计时器代码。我的代码...

<script>
var x = Math.floor(Math.random() * 20) + 1;
var y = Math.floor(Math.random() * 28) + 1;


for (i = 0; i < 5; i++) { 
        var wnd = window.open("http://www.random.com/x=" + x + "y=" + y);
        setTimeout(function() {
        wnd.close();
    }, 5000);
  };
</script>

【问题讨论】:

    标签: javascript for-loop timer settimeout window.open


    【解决方案1】:

    您必须将代码更改为:

    var x = Math.floor(Math.random() * 20) + 1;
    var y = Math.floor(Math.random() * 28) + 1;
    
    
    var timesRun = 0;
    var interval = setInterval(function(){
        timesRun += 1;
        if(timesRun === 5){
            clearInterval(interval);
        }
            var wnd = window.open("http://www.random.com/x=" + x + "y=" + y);
            setTimeout(function() {
                wnd.close(); 
            }, 5000);
    }, 5000); 
    

    您的代码只会打开 5 个窗口,然后在 5 秒后一一关闭。这段代码应该做你想做的事

    【讨论】:

      【解决方案2】:

      您可能需要等待一扇窗户关闭后再打开另一扇窗户!代码看起来像这样:

      function openURL(counter, max) {
        var x = Math.floor(Math.random() * 20) + 1;
        var y = Math.floor(Math.random() * 28) + 1;
        var url = "http://www.random.com/?x=" + x + "y=" + y;
      
        if(counter <= max) {
          var wnd = window.open(url);
          setTimeout(function() {
              wnd.close();
              openURL(++counter, max);
          }, 5000);
        }
      }
      
      openURL(1, 5);
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多