2014-02-13 42 views
1

我有點困惑,我已經從其他地方讀過,超時/間隔是每隔x秒運行一次Javascript的最佳方式。我必須這樣做,以便我的函數每1秒運行一次,因爲這是我使用的API的規則。

我的代碼如下:

$.each(match_details_json.result.players, function(index, v){ 
    if (v.account_id == 38440257){ //finds desired playerid 
     var match_id_2 = matches[i]; 
     hero = v.hero_id; 
     playerpos = v.player_slot; 
     var kills = v.kills; 
     var deaths = v.deaths; 
     var assists = v.assists; 
     var kda = ""+kills+"/"+deaths+"/"+assists+""; 
     console.log(match_id_2, hero, playerpos, result, gamemode, kda); 
     callback(); 
     console.log(match_id_2, hero, result, gamemode, kda); 
     h=h+1; 
     setTimeout(get_match_details(h), 10000); 
     i=i+1; 
    } 
    else{ 
     console.log('Not desired player, skipping...'); 
    } 

}); 

很多亂碼出現。但重要的部分是setTimeout(get_match_details(h), 10000);

無論這是否正確,那就是我試圖說「在10秒內再次運行此功能」並繼續,直到每個方法完成。它不起作用。

如果有必要,這是我get_match_details功能:

function get_match_details(){ 
     $.ajax({ 
      url: 'php/ApiMatchPull.php', 
      data: {accountid:'38440257', querytype:'GetMatchDetails', querycondition1:'match_id='+matches[h]}, 
      success: function (data) { 
       console.log ('Match Details were was pulled successfully'); 
       match_details_json = data; 
       matchdetailsfill(checkvalidity); 
      } 
     }); 
} 

預先感謝您。

回答

4

這正是什麼setInterval & clearInterval是。

所以不是setTimeout的,你可以使用它是這樣的:

var timer = setInterval(function() { 

     get_match_details(h); 

}, 1000);        // for every second 

而當你想停止它,使用:

clearInterval(timer); 
0

,您執行此功能get_match_details immedatiately,更改代碼到

setTimeout(function() { 
    get_match_details(h) 
    }, 10000); 

你的代碼中會發生什麼,你循環粗暴所有的玩家,並在10秒後儘可能多的Ajax調用(get_match_details)。

如果你想要讓每個阿賈克斯之間10秒的間隔叫你有你的方式重構爲這樣的事情:

var l = [1,2,3,4,5]; 
    var c = l.length; 
    var ix = -1; 
    ajax = function(n) { 
    alert('do some ajax with ' + n) 
    } 
    call = function() { 
    if(c > ++ix) { 
     ajax(l[ ix ]); 
     setTimeout(function() { call(); }, 1000); 

    } 
    } 
    call();