0

I have the following code that when working correctly should open link 1 in the iframe, wait 3 seconds, then open link 2 in the iframe, wait 3 seconds, etc..

Currently it's skipping straight to the last value in the array (the last link).

Any JS expert takers?

 <html>
 <head></head>
 <body>

 <a href="http://www.google.com">Google</a><br />
 <a href="http://www.thinkgeek.com">ThinkGeek</a><br />
 <a href="http://www.themetapicture.com">The Meta Picture</a>

 <iframe src="http://www.google.com" id="myid" name="main" width="1024" height="768">
 </iframe>

 <script>
 function getLinksArray() {
     for (var i = 0; i < document.links.length; i++) {
         var linx = document.links[i].href;

         // create a closure for each loop iteration
         (function(linx) {
           setTimeout(function() {
             openLinks(linx);
           }, 3000);
         }(linx));

     }
 }

 function openLinks(link) {
 document.getElementById("myid").src = link;
 }

 window.onload = getLinksArray();
 </script>
 </body>
 </html>
2
  • The loop will create the timeouts super quick so the first one will wait 3 seconds only to have the 3rd be milliseconds behind. Open links should create the next timeout. Commented Feb 5, 2013 at 21:49
  • 1
    All of your events would go off in three seconds — multiply 3000 by the current iteration count. Commented Feb 5, 2013 at 21:49

3 Answers 3

3

You probably want 3000 * i as your delay, otherwise all execute after 3000ms (3 seconds). and since they're executed serially, the last one is the one that's noticed.

// ...
setTimeout(function(){
  // ...
}, 3000 * i);
// ...
Sign up to request clarification or add additional context in comments.

Comments

0

I'm pretty sure something like this should do the trick, without creating longer and longer delays. Haven't performance tested both though, so can't say which is best - just wanted to make sure you were aware of another option.

var linx = document.links;
(function loadLink(i) {          
    setTimeout(function () {   
        document.getElementById("myid").src = linx[i].href;
        if(linx[++i])
        {
            loadLink(i);
        }
    }, 3000)
})(0);

1 Comment

Haha, got so distracted while writing my answer someone else posted a very similar one before me.. ah well, still a different approach!
0

You might want to simply make the iteration itself timed:

function loadLink(i) {
    document.getElementById("myid").src = document.links[i].href;
    if (i < document.links.length) {
        window.setTimeout(function() { loadLink(i+1) }, 3000);
    }
}

window.onload = loadLink(0);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.