簡體   English   中英

Javascript-數組循環問題

[英]Javascript - Problems with Loop with Array

我有以下代碼,當正常工作時,應在iframe中打開鏈接1,等待3秒,然后在iframe中打開鏈接2,等待3秒,依此類推。

當前,它直接跳到數組中的最后一個值(最后一個鏈接)。

有JS專家參加者嗎?

 <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>

您可能希望將3000 * i作為您的延遲,否則全部在3000ms(3秒)后執行。 並且由於它們是串行執行的,因此最后一個是被注意到的那個。

// ...
setTimeout(function(){
  // ...
}, 3000 * i);
// ...

您可能想簡單地使迭代本身計時:

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);

我很確定這樣的事情應該可以解決,而不會造成越來越長的延遲。 雖然尚未對兩者進行性能測試,所以不能說是最好的-只是想確保您知道其他選擇。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM