2017-06-06 32 views
4

我想創建一個頁面,將運行一些給定的URL,及時這將是一個數據庫填充到一個數組中的URL填充列表。我使用了一些我已經修改的代碼,但是我不希望它繼續循環,我只是希望它在列表完成後停止。JavaScript URL looper

因此,基本上加載第一個URL,加載頁面後等待0.5秒,然後移動到下一個,直到URLS列表完成。

但是,我的代碼保持循環。我如何防止這種情況?

var urls1 = 
 
[ 
 
\t 'http://localhost:8500/SupportTools/t1.cfm', 
 
\t 'http://localhost:8500/SupportTools/t2.cfm', 
 
\t 'http://localhost:8500/SupportTools/t3.cfm', 
 
\t 'http://localhost:8500/SupportTools/t4.cfm', 
 
\t 'http://localhost:8500/SupportTools/t5.cfm' 
 
]; 
 

 
function showUrl1(idx) 
 
{ 
 
\t var f1 = document.getElementById("f1"); 
 
\t f1.onload = function() 
 
\t { 
 
\t \t var next = ++idx % urls1.length; 
 
\t \t setTimeout(function() 
 
\t \t { 
 
\t \t \t showUrl1(next); 
 
\t \t }, 500); 
 
\t } 
 
\t f1.src = urls1[idx]; 
 
} 
 

 
function start() 
 
{ 
 
\t showUrl1(0); 
 
}
<iframe class="show1" id="f1" src="about:blank"></iframe>

+0

%返回餘數。 所以你的下一個在第5個循環中重置爲0。 – neetesh

回答

1

不要showUrl時,列表結束

function showUrl1(idx) 
{ 
    var f1 = document.getElementById("f1"); 
    f1.onload = function() 
    { 

     var next = idx === urls1.length? null: ++idx ; 
     setTimeout(function() 
     { if(next != null){ 
       showUrl1(next); 
      } 

     }, 500); 
    } 
    f1.src = urls1[idx]; 
} 
+0

這工作完美,非常感謝你,我現在唯一要做的唯一事情就是顯示算在一個分區:) –

+0

@AdamWalters什麼數? –

3

它循環的原因是因爲你使用的remainder operator %。只需檢查以查看next是否大於或等於該長度,然後不要致電setTimeout()。我更改了代碼片段,以便您可以在控制檯中看到它的輸出結果,但您應該明白。

var urls1 = [ 
 
    'http://localhost:8500/SupportTools/t1.cfm', 
 
    'http://localhost:8500/SupportTools/t2.cfm', 
 
    'http://localhost:8500/SupportTools/t3.cfm', 
 
    'http://localhost:8500/SupportTools/t4.cfm', 
 
    'http://localhost:8500/SupportTools/t5.cfm' 
 
]; 
 

 
function showUrl1(idx) { 
 

 
    if (idx >= urls1.length) { 
 
    return; 
 
    } 
 
    console.log(urls1[idx]); 
 
    var next = ++idx; 
 
    setTimeout(function() { 
 
    showUrl1(next); 
 
    }, 500); 
 

 

 
} 
 

 
function start() { 
 
    showUrl1(0); 
 
} 
 

 
start();

+0

這工作完美,非常感謝你,我現在唯一要做的就是顯示在一個div中的計數:) –