2014-02-13 1 views
1

나는 조금 혼란 스럽다. 시간 초과/간격이 매 x 초마다 자바 스크립트에서 함수를 만드는 가장 좋은 방법이라는 것을 다른 곳에서 읽었다. 이 API는 내가 사용하고있는 API의 규칙이므로 1 초마다 내 함수가 실행되도록 만들어야합니다. 지저분한 코드의

$.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 초 후에이 기능을 실행하십시오"라고 말하면서 각 방법이 끝날 때까지 계속 진행합니다. 작동하지 않습니다.

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); 
      } 
     }); 
} 

가 사전에 감사합니다

필요한 경우, 여기 내 get_match_details 기능입니다.

답변

4

이것은 정확히 setInterval & clearInterval입니다. 그래서 그 대신의 setTimeout의

, 당신은 그것을 같은 것을 사용할 수 있습니다

var timer = setInterval(function() { 

     get_match_details(h); 

}, 1000);        // for every second 

을 그리고 당신이 그것을 중지, 사용하고자 할 때 :

clearInterval(timer); 
0

당신은, immedatiately 기능 get_match_details을 실행 코드를 변경

코드에서 어떻게됩니까
setTimeout(function() { 
    get_match_details(h) 
    }, 10000); 

에 당신 루프 일이 거친 모든 플레이어와 10 초 후에 많은 Ajax 호출 (get_match_details)이 동시에 생성됩니다.

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(); 
: 각 아약스 사이에 십초 간격을 원한다면

이 같은 당신의 접근 방식을 리팩토링해야 전화

관련 문제