Jump to content
  • Advertisement
Sign in to follow this  
Code_Strike

Multiple window.setTimeout's not executing

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

If you intended to correct an error in the post then please contact us.

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>
function open_linker(link, incr)
{
//alert("Yay");
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 linky = new Array("http://yahoo.com","http://msn.com","http://google.com","http://cnbc.com");

var nap_time = [5000];
for(g = [0]; g < [4]; g++)
{
window.setTimeout(open_linker(linky[g],g),  nap_time, nap_time);
nap_time += [5000];
}
</script>
What am I missing

Share this post


Link to post
Share on other sites
Advertisement
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:
window.setTimeout(open_linker(linky[g],g), nap_time, nap_time);
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.)

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!