2013-03-26 95 views
0

我想用setTimeout每10秒重复一次函数。我的功能是:我的setTimeout不尊重延迟

dateInLive = function() { 
    crono = function(){ 
     setTimeout(function() { 
     $('.datePoste').each(function(){ 
       $(this).load('in_live.php','in_live='+$(this).attr('id')) 
      }); 
     crono(); 
     } 
     ,10000); 
    } 
    crono(); 
} 

但是,它确实是随机的;有时在15s之后重复,有时在3s之后,有时在6s之后。

+0

它看起来像你不小心叫了两次crono()。尝试从setTimeout中删除crono()调用? – lifetimes 2013-03-26 15:51:06

+0

看起来你可以使用'setInterval()'而不是'setTimeout()'来获得更多的好处。 – 2013-03-26 15:51:36

+2

@ user125697不,他在'setTimeout()'中调用它来重复该函数。相反,最好使用'setInteral()'。 – Antony 2013-03-26 15:51:37

回答

2

召回crono()只有当所有的Ajax请求完成:

function crono(){ 
    setTimeout(function() { 
     var arr = []; 
     $('.datePoste').each(function(){ 
      var self = this; 
       xhr = $.get('in_live.php', {in_live : this.id}, function(data) { 
        $(self).html($.parseHTML(data)); 
       }); 
      arr.push(xhr); 
     }); 
     $.when.apply($, arr).done(crono); 
    }, 10000); 
} 
+0

啊,我没有看到你的答案,然后我张贴我的。虽然有一个问题,我不认为.load返回一个xhr,但我可能是错误的。我非常确定从.promise返回的promise对象是用于这种方式的动画队列,而不是ajax请求。 – 2013-03-26 16:08:24

+0

@KevinB - 不确定是否加载,但所有其他ajax方法返回一个承诺,只是无法找到load()上的任何东西? – adeneo 2013-03-26 16:09:37

+0

好吧,因为.load会返回一个jQuery集合,这就是我的想法。在jQuery集合中使用.promise()(这就是.when所做的)会获得一个promise对象,该对象可以解决所有现有动画完成时的情况。目前我还没有一个简单的方法来测试它。 – 2013-03-26 16:10:29

0

在创建新的超时之前,你正在做某件事,这意味着肯定会有“某种”延迟。

看看setInterval()函数。

0

你只是在错误的地方有crono()函数。

dateInLive = function() { 
crono = function(){ 
setTimeout(function() { 
     crono(); 
     $('.datePoste').each(function(){ 
       $(this).load('in_live.php','in_live='+$(this).attr('id')) 
      }); 
     } 
     ,10000); 
    } 

} 
2

您正在使用setTimeout来运行重复事件。

这是正确的(其他人建议使用setInterval代替,但有问题)。

但是,您并未在随后的调用中设置超时 - 您只是直接调用crono()函数,所以在初始超时延迟之后,它会立即开始自我调用,并一次又一次地反复(直到它耗尽堆栈空间)。

您每次调用该函数时都需要调用setTimeout()。重新编码它是这样的:

dateInLive = function() { 
    crono = function(){ 
     $('.datePoste').each(function(){ 
      $(this).load('in_live.php','in_live='+$(this).attr('id')) 
     }); 
     setTimeout(crono,10000); 
    } 
    setTimeout(crono,10000); 
} 
+2

Does'nt看起来像这是我的问题。超时在函数内部,并且该函数仅在该超时内被再次调用。 – adeneo 2013-03-26 15:58:02

+1

也可以使用函数声明语法。 – Pointy 2013-03-26 15:58:17

+0

我仍然有同样的问题 – 2013-03-26 16:05:13

2

在这种情况下,我会用延迟对象。

function crono(){ 
    setTimeout(function() { 
     var defArr = []; 
     $('.datePoste').each(function(i,el){ 
      var deferred = $.Deferred(); 
      defArr.push(deferred.promise()); 
      $(this).load('in_live.php','in_live='+$(this).attr('id'), function() { 
       deferred.resolve(); 
      }); 
     }); 
     $.when.apply($,defArr).done(crono); 
    }, 10000); 
} 

否则它将要求所有的部分,然后当接收到所有部分,等待10秒钟,并再次请求他们,避免在速度较慢的网络情况堆砌要求这样。