问题
I am looking for javascript code which will open new tabs(windows) automatically after specific interval of time.
Once first url is executed, setTimeout()/setIntervals()'s are ignored?? Please help!
<html>
<head>
<script type="text/javascript">
function open_win() {
setInterval(window.open("http://www.google.com"), 1000);
setInterval(window.open("http://www.yahoo.com"), 1000);
setInterval(window.open("http://www.bing.com"), 1000);
}
</script>
</head>
<body>
<form>
<input type=button value="Open Windows" onclick="open_win()">
</form>
</body>
Thank you
回答1:
First of all, you don't want to use setInterval
for this, setInterval:
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
You want to use setTimeout which:
Calls a function or executes a code snippet after a specified delay.
The next problem is that setTimeout
wants a function as its first argument but window.open returns a reference to a window object. You want to wrap those window.open
calls inside functions:
function open_win() {
setTimeout(function() { window.open("http://www.google.com") }, 1000);
setTimeout(function() { window.open("http://www.yahoo.com") }, 1000);
setTimeout(function() { window.open("http://www.bing.com") }, 1000);
}
Your version would open the Google tab because the window.open("http://www.google.com")
call would be executed while building the argument list for the first setInterval
call. Presumably you're getting an exception or something from setInterval
when you pass it a window reference so the rest of them aren't even reached.
来源:https://stackoverflow.com/questions/18029330/delay-after-opening-a-new-tab-using-window-open