2013-03-26 100 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秒鐘,並再次請求他們,避免在速度較慢的網絡情況堆砌要求這樣。