2017-01-05 25 views
-3

我怎樣才能讓這個間隔功能停止運行時theImage長度等於更多的是0,運行功能,每2秒鐘,直到varible改變

我的代碼

var theImages = $('.awesome-slider .slides img'); 

function checkImages(){ 
    theImages = $('.awesome-slider .slider img'); 
    // other stuff happens here but only want it to run once 
} 

if(theImages.length == 0){ 
    window.setInterval(function(){ 
      checkImages(); 
    }) 
} 

theImages lenght併成爲最終超過0,但爲什麼間隔函數仍在運行?

+0

這是不正確的代碼,請審查,並張貼正確。 –

+4

*「爲什麼間隔函數繼續運行?」*因爲你永遠不會取消它......你永遠不會說它停止,所以它繼續前進。 – epascarello

回答

1

使用clearInterval()

let interval = window.setInterval(function() { 

       checkImages(); 

       if (theImages.length == 0) { 
        clearInterval(interval); 
       }; 

       }, 2000); 
+0

這一直持續運行:/ –

+0

@AlexK將其更改爲'if(theImages.length!= 0){' – Igor

+0

Ohhhhhhhhhhh哇我錯過了!很好用!謝謝 –

0

使用window.setTimeout代替間隔。

按照定義,如果不明確地關閉間隔,間隔將繼續進行。 你需要setTimeout,它只會運行一次。經過圖像長度測試後,如果需要可以創建另一個實例

1

我建議您使用setTimeout而不是setInterval

var theImages = $('.awesome-slider .slides img'); 
 

 
function checkImages() { 
 
    if (theImages.length !== 0) { 
 
    setTimeout(function() { 
 
     checkImages(); 
 
    }, 2000); 
 
    } 
 
} 
 

 
checkImages();

+1

這裏你不需要'clearTimeout',條件應該是相反的 – Igor

+0

@Igor是的。謝謝你,小夥伴。 –

+0

@Alex K Dude,'setTimeout'是'setInterval'非常簡單的解決方案。你應該考慮使用它。 –