Can someone tell me how to make my URLs properly loop into the window.open
I created? I’m wondering if the loop is the right answer to make each URL rotate based on
You are not updating the value of rotate..
Try doing this
<script type="text/javascript">
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];
var rotate = 0;
function goRandom( )
{
rotate= (rotate+1) % urls.length;
var newwin = window.open(
urls[ rotate ],
"POPUP",
"height=400,width=600,scrollbars=yes" );
}
var loop= setInterval(goRandom, 5000);
</script>
While the other answers are technically correct, here's a simplied version if you're just starting out with js, all that %
can be confusing.
// setup urls
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];
// rotate is a global variable so can be accessed anywhere
var rotate = 0;
function goRandom( )
{
var newwin = window.open(
urls[ rotate ],
"POPUP",
"height=400,width=600,scrollbars=yes" );
// move to the next array position
rotate++;
// Check if at the end of the array and move back to the beginning
if (rotate >= urls.length)
rotate = 0;
}
// Keep going indefinitely
setInterval(goRandom, 5000);
Now, your function is called goRandom()
while this will goSequence()
(or goNext()
), so you can change this without any form of loop to pick a random url (though your loop var is called 'rotate' so maybe not what you wanted).
// setup urls (global so accessed from anywhere)
var urls = ["http://www.espn.com","http://www.disney.com","http://www.codingforums.com"];
function goRandom( )
{
// get a random url
var rotate = Math.floor(Math.random() * (urls.length - 1));
var newwin = window.open(
urls[ rotate ],
"POPUP",
"height=400,width=600,scrollbars=yes" );
}
// Keep going indefinitely
setInterval(goRandom, 5000);
Just change
urls[ rotate ],
to
urls[ (rotate++) % urls.length ],
The index is incremented each iteration and % urls.length
(% is used for getting the remainder after division, hence it ensures the result never grows beyond the array size). You can try it here (remember to allow popups).