0

I need to build a program that opens a website, waits for about 5 sec, then closes the website and opens a different website, it needs to loop about 5 times. The websites' URL will change just like in my code. I just don't know how to work the whole timer codes. My code...

<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>
Madda
  • 21
  • 5

2 Answers2

0

You have to change your code to:

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); 

Your code will just open the 5 windows and then close them after 5 seconds, one by one. This code should do what you want

0

You may want to wait for one window close to open the another one! The code will look somehting like this:

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);
nanndoj
  • 6,580
  • 7
  • 30
  • 42
  • How can I make the x's and y's never repeat? – Madda Dec 26 '14 at 23:05
  • There's many different answers. This one should solve your problem http://stackoverflow.com/questions/10756119/how-to-genrate-random-numbers-with-no-repeat-javascript – nanndoj Dec 26 '14 at 23:07