2012-08-14 110 views
0

在這裏我找到了一個循環(遞歸函數)延遲的例子,並用於它自己的目的。問題是,成功添加div我需要停止循環,但這裏是遞歸函數,所以break會引發錯誤。如何停止功能

我想是這樣的:

(function myLoop(i){ 
    console.log($("input[name='show']").is(':visible')); 
    if($("input[name='show']").is(':visible')) 
     return false; 
    setTimeout(function(){ 
     $.getScript('index.php?ping=true', function(data){ 
      if(ping){ 
       $('#input').append('<input width="320" type="image" height="240" border="0" src="http://'+url+':'+port+'/?up" name="show">'); 
      } 
     }); 
     if (--i) myLoop(i); 
    }, 7000) 
})(10); 

,但是它停止添加第二個div之後。據我所知,我需要以某種方式使用回調,如果?

enter image description here

UPDATE: 解決剛纔添加如果(--i)myLoop(我)自己的問題;到代碼

+1

而不是遞歸,爲什麼不使用setInterval/clearInterval? – Flash 2012-08-14 07:07:00

+0

請創建一個演示:jsfiddle.net – Diode 2012-08-14 07:08:35

回答

0

您需要存儲對您的setTimeout和使用clearTimeout的引用。

var timeout = setTimeout(function(){ 
    if (success) { 
     clearTimeout(timeout); 
    } 
}); 
+0

我更新了我的帖子 - 有屏幕。 – user1564141 2012-08-14 07:11:30

1

一個更好的方法可能會再打電話的功能,如果它實際上是失敗,只是設置了限制或類似的東西:

var i=0, limit=10; 

function getSomething() { 
    if (!$("input[name='show']").length) { 
     var XHR = $.getScript('index.php?ping=true'); 
     XHR.done(function(data){ 
      if(ping){ 
       $('#input').append('<input width="320" type="image" height="240" border="0" src="http://'+url+':'+port+'/?up" name="show">'); 
      } 
     }).fail(function() { 
      if (i<limit) setTimeout(getSomething, 7000); 
      i++; 
     }); 
    } 
});  

setTimeout(getSomething, 7000); 

察看此元素存在should'nt真的neccessary因爲它可能不會存在,直到函數不再失敗等。另外,你從哪裏得到變量ping,url和端口,因爲它們沒有在任何地方定義?

+0

http://api.jquery.com/jQuery.ajax/其關於數據 – user1564141 2012-08-14 07:26:38

+0

if(ping =='true'){ \t $('#input')。append(''); } else \t if( - i)myLoop(i); – user1564141 2012-08-14 07:31:15