如何停止功能

时间:2012-08-14 07:03:23

标签: javascript jquery loops recursion

这里我找到了一个循环(递归函数)延迟的例子,并用于它自己的目的。问题是,成功添加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后它才会停止。据我所知,我需要以某种方式使用if?

上的回调

enter image description here

更新 自己解决了这个问题,只需添加if(--i)myLoop(i);到了拿稿子

2 个答案:

答案 0 :(得分: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);

检查元素是否存在不应该是必要的,因为它可能不会存在,直到函数不再失败等。此外,你从哪里得到变量ping,url和port,因为它们没有在任何地方定义?

答案 1 :(得分:0)

您需要存储对setTimeout和使用clearTimeout的引用。

var timeout = setTimeout(function(){
    if (success) {
        clearTimeout(timeout); 
    }
});
相关问题