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.