• 14
• 12
• 9
• 10
• 13

# Multiple window.setTimeout's not executing

This topic is 3067 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm trying to use setTimeout on a loop, but it's only executing once. It should open each link in a new window every five seconds, but instead it executes once and stops. Here's my code(note that the forum code is making my "plusequal 5000" line look like "= [5000]" for some reason. In and out of the code box).
<script>
{
if(incr == [0]) window.open(link, "GD1");
if(incr == [1]) window.open(link, "GD2");
if(incr == [2]) window.open(link, "GD3");
if(incr == [3]) window.open(link, "GD4");
}

var nap_time = [5000];
for(g = [0]; g < [4]; g++)
{
nap_time += [5000];
}
</script>

What am I missing

##### Share on other sites
setTimeout expects a string of code to execute or a function object to call when the timeout occurs. Instead you've actually calling the open_linker function when you do:
Hence the action occurs immediately, and since open_linker doesn't return what setTimeout wants, the script dies. (Check your browser's JS debugger!)

So, instead you probably meant:
window.setTimeout("open_linker(linky[" + g + "]," + g + ")", nap_time, nap_time);

However, you can do what you want better with a closure:

function windowOpen(url, name) {	return function () { window.open(url, name) }}var linky = ["http://yahoo.com", "http://msn.com", "http://google.com", "http://cnbc.com"];for(var g = 0; g < linky.length; ++g)    window.setTimeout(windowOpen(linky[g], "GD" + (g + 1)), g * 5000); // unfortunately we can't // pass in params for the function object in IE, hence the use of another scope to hold its parameters

(Yeah, the numbers getting square brackets around them is a known bug in GD's forums.. just specify something else like C++ instead.)