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 后才会停止。据我了解,我需要以某种方式使用回调 if?

在此处输入图像描述

更新: 自己解决了这个问题,只是添加了 if (--i) myLoop(i); 到 getscript

4

2 回答 2

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,因为它们没有在任何地方定义?

于 2012-08-14T07:20:01.977 回答
0

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

var timeout = setTimeout(function(){
    if (success) {
        clearTimeout(timeout); 
    }
});
于 2012-08-14T07:07:17.643 回答