2012-08-14 105 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