【问题标题】:setInterval + for Loop skipping iterationssetInterval + for 循环跳过迭代
【发布时间】:2015-08-24 20:12:13
【问题描述】:

我目前的项目有很多代码,所以我会尽力解释我遇到的非常奇怪的问题。

我有一个名为 proDatabase 的数组数组,长度为 126 个条目,每个条目是一个长度为 4 个条目的数组。

我有一个按钮,单击该按钮后,每1.05 秒启动一个setInterval 函数以运行一个名为“getScore”的函数

getScore 包含对 API 的 ajax 调用,该 API 返回一个 JSON 对象,我从该对象收集了一堆数据,然后执行名为 calculateHmc 的计算函数。

calculateHmc 执行大计算并将值推送到全局数组。控制台然后记录这个数组的值以表明它是成功的。

我遇到的问题是,当我运行这个脚本大约需要 2.5 分钟(126 个条目 x 每个条目约 1.05 秒)时,结果会随着运行而变化。我的意思是,有时它会成功获取条目 5、6、7、8、9 的数组,但不会成功获取 10 和 11,而另一次它会获取 5、7、8、10、11 的数组,但不是 6 和 9。

我想也许是我进行 AJAX 调用的速度太快了,但我尝试将延迟设置为 2-5 甚至 9 秒,但问题仍然存在。

我最初使用带有 setTimeout 延迟的 for 循环并更改为 setInterval,因为我认为它可能更适合进行 AJAX 调用。

这是肉和土豆:

var proDatabase = [
    ["fredy122", 266, 19286794, "euw"],
    ["soeren", 103, 47199162, "na"],
    ["voyboy", 84, 19134540, "na"],
    ["krepo", 12, 19307647, "euw"],
    ["kiwikid", 32, 24332462, "na"],
    ["froggen", 34, 29762147, "na"],
    ["FnaticYellOwStaR", 1, 254943, "euw"],
    ["dingdongchingchong", 22, 38332654, "kr"],
    ["kiwikid", 432, 24332462, "na"],
    ["wingsofdeathx", 268, 19660288, "na"],
    ["liquidxpecial", 201, 19199530, "na"],
    ["aphromoo", 53, 442232, "na"],
    ["wingsofdeathx", 63, 19660288, "na"],
    ["sneaky", 51, 1621, "na"],
    ["easyhoon", 69, 14080738, "kr"],
    ["azingy", 31, 22479740, "na"],
    ["jin air cpt jack", 42, 1560617, "kr"],
    ["voyboy", 122, 19134540, "na"],
    ["shiphtur", 131, 19967304, "na"],
    ["arrow", 119, 9161207, "kr"],
    ["calitrlolz8", 36, 21059607, "na"],
    ["svenskeren", 245, 37220473, "eune"],
    ["meteos", 60, 44008519, "na"],
    ["theoddone", 28, 60783, "na"],
    ["jin air chaser", 81, 7941870, "kr"],
    ["azingy", 9, 22479740, "na"],
    ["jin air trace", 114, 35214500, "na"],
    ["xpeke", 105, 47409145, "na"],
    ["overpow", 3, 30968712, "euw"],
    ["fredy122", 41, 19286794, "euw"],
    ["darien", 86, 295022, "euw"],
    ["jin air cpt jack", 150, 1560617, "kr"],
    ["theoddone", 79, 60783, "na"],
    ["skt t1 bengi", 104, 1255867, "kr"],
    ["dyrus", 120, 5908, "na"],
    ["voyboy", 74, 19134540, "na"],
    ["dyrus", 39, 5908, "na"],
    ["smoothie", 40, 20823651, "na"],
    ["watch", 59, 1241252, "kr"],
    ["voyboy", 24, 19134540, "na"],
    ["ryu", 126, 3617422, "kr"],               //["ryu", 126, 3617422, "kr"],
    ["doublelift", 222, 20132258, "na"],
    ["wildturtl", 429, 42060215, "na"],
    ["C9 Lemon", 43, 44979325, "na"],
    ["fredy122", 30, 19286794, "euw"],
    ["voyboy", 38, 19134540, "na"],
    ["nien", 55, 35717979, "na"],
    ["rng alex ichy", 10, 65009177, "na"],
    ["fredy122", 85, 19286794, "euw"],
    ["voyboy", 121, 19134540, "na"],
    ["renegade maple", 96, 31804754, "na"],
    ["c9 jensen", 7, 68479082, "na"],
    ["svenskeren", 64, 37220473, "eune"],
    ["krepo", 89, 19307647, "euw"],
    ["marin", 127, 23041646, "kr"],
    ["img steeel4ckv2", 236, 69399083, "na"],
    ["overpow", 117, 30968712, "euw"],
    ["kami", 99, 4442388, "br"],
    ["voyboy", 90, 19134540, "na"],
    ["theoddone", 54, 60783, "na"],
    ["dyrus", 57, 5908, "na"],
    ["choi insec", 11, 1567183, "kr"],
    ["theoddone", 21, 60783, "na"],
    ["overpow", 82, 30968712, "euw"],
    ["aphromoo", 25, 442232, "na"],
    ["fnaticyellowstar", 267, 254943, "euw"],
    ["suryD", 75, 89197, "na"],
    ["xpecial", 111, 21744791, "na"],
    ["h0r0", 76, 2191624, "kr"],
    ["crumbzz", 56, 38789432, "na"],
    ["crumbzz", 20, 38789432, "na"],
    ["theoddone", 2, 60783, "na"],
    ["pobelter", 61, 2648, "na"],
    ["azingy", 80, 22479740, "na"],
    ["voyboy", 78, 19134540, "na"],
    ["lustboy", 133, 58849083, "na"],
    ["unstoppable move", 33, 68159251, "na"],
    ["theoddone", 421, 60783, "na"],
    ["dyrus", 58, 5908, "na"],
    ["svenskeren", 107, 37220473, "euw"],
    ["zionspartan", 92, 19738326, "na"],
    ["dyrus", 68, 5908, "na"],
    ["hide on bush", 13, 4460427, "kr"],
    ["loulex", 113, 20050482, "euw"],
    ["fnaticyellowstar", 35, 254943, "euw"],
    ["lustboy", 98, 58849083, "na"],
    ["theoddone", 102, 60783, "na"],
    ["skt t1 bengi", 27, 1255867, "kr"],
    ["kev1n", 14, 50333030, "eune"],
    ["jin air cpt jack", 15, 1560617, "kr"],
    ["nightblue3", 72, 33320460, "na"],
    ["godpiglet", 37, 65409090, "na"],
    ["adrian", 16, 3267, "na"],
    ["vizicsacsi", 50, 33779494, "na"],
    ["overpow v1", 134, 19479122, "euw"],
    ["voyboy", 223, 19134540, "na"],
    ["kami", 91, 4442388, "br"],
    ["dunno lol", 44, 37802535, "euw"],
    ["overpow", 17, 30968712, "euw"],
    ["aphromoo", 412, 442232, "na"],
    ["sneaky", 18, 1621, "na"],
    ["yellowstar", 48, 42323523, "eune"],
    ["save", 23, 19134540, "na"],
    ["shiphtur", 4, 19967304, "na"],
    ["wildturtle", 29, 521955, "na"],
    ["trick2g", 77, 19975245, "na"],
    ["i am bjerg", 6, 49159160, "na"],
    ["turtle the cat", 110, 18991200, "na"],
    ["wildturtle", 67, 521955, "na"],
    ["fly", 45, 1570144, "kr"],
    ["dodo8", 161, 19245823, "na"],
    ["crumbzz", 254, 38789432, "na"],
    ["froggen", 112, 29762147, "na"],
    ["pain kamikat", 8, 479257, "br"],
    ["azingy", 106, 22479740, "na"],
    ["nightblue3", 19, 3320460, "na"],
    ["nightblue3", 62, 33320460, "na"],
    ["pain kamikat", 101, 479257, "br"],
    ["nightblue3", 5, 3320460, "na"],
    ["dunamis or shiphtur", 157, 44989349, "na"],
    ["c9 jensen", 83, 68479082, "na"],
    ["theoddone", 154, 60783, "na"],
    ["hide on bush", 238, 4460427, "kr"],
    ["theoddone", 115, 60783, "na"],
    ["korean characters... fly", 26, 2706560, "kr"],
    ["xpooks", 143, 174035, "euw"]
];

$(document).ready(function() {

$("#sendButton").click(function () {

    var counter = 0;
    var n = setInterval(function () {

        var summonerName = proDatabase[counter][0];
        var summonerId = proDatabase[counter][2];
        var championNumber = proDatabase[counter][1];
        var region = proDatabase[counter][3];

        console.log(summonerId + " " + championNumber);
        // console.log("Initializing function...");

        getScore(summonerId, championNumber, region, summonerName);
        // console.log("passed the getScore function")
        console.log(counter);
        counter++;
        if (counter == 127) {
            clearInterval(n);
        }
    }, 1050, counter);

});
});

function getScore(summonerId, championNumber,  region, summonerName) {

$.ajax({
    dataType: "json",
    type: 'GET',
    url: 'https://' + region + '.api.pvp.net/api/lol/' + region + '/v2.2/matchhistory/' + summonerId + '?championIds=' + championNumber + '&queueType=NORMAL_5x5_BLIND,NORMAL_5x5_DRAFT,RANKED_SOLO_5x5,RANKED_PREMADE_5x5,NORMAL_5x5_DRAFT,RANKED_TEAM_5x5&beginIndex=0&endIndex=5&api_key=***********************',
    success: function (data, state) {

        /*  if(state == "success"){
            console.log("OBJECT RETURNED (SUCCESS)");
        }else{
            console.log("SUMMONER COULD NOT BE FOUND. LIKELY WRONG REGION. CHECK LOLKING");
        } */

        console.log("LOOKING UP GAMES FOR " + summonerName + " WITH A SUMMONER ID OF " + summonerId + "IN REGION "+ region + "FOR CHAMPION NUMBER " + championNumber);

        for (i = 0; i < 5; i++) {

            //v1.1.0

            if (data.matches[i].participants[0].stats.firstBloodKill == true){
                firstBloodArray[i] = 1;
            }else{
                firstBloodArray[i] = 0;
            }

            if (data.matches[i].participants[0].stats.firstTowerKill == true){
                firstTowerArray[i] = 1;
            }else{
                firstTowerArray[i] = 0;
            }

            if (data.matches[i].participants[0].stats.firstTowerKill == true){
                firstInhibitorArray[i] = 1;
            }else{
                firstInhibitorArray[i] = 0;
            }

            damageDealtArray[i] = data.matches[i].participants[0].stats.totalDamageDealt;
            healingDealtArray[i] = data.matches[i].participants[0].stats.totalHeal;
            damageTakenArray[i] = data.matches[i].participants[0].stats.totalDamageTaken;
            inhibitorArray[i] = data.matches[i].participants[0].stats.inhibitorKills;
            towerArray[i] = data.matches[i].participants[0].stats.towerKills;

            //timeline arrays

            tl_arr_cspm_zero_ten[i] = data.matches[i].participants[0].timeline.creepsPerMinDeltas.zeroToTen;
            tl_arr_cspm_ten_twenty[i] = data.matches[i].participants[0].timeline.creepsPerMinDeltas.tenToTwenty;

            if(data.matches[i].participants[0].timeline.creepsPerMinDeltas.twentyToThirty != undefined) {
                tl_arr_cspm_twenty_thirty[i] = data.matches[i].participants[0].timeline.creepsPerMinDeltas.twentyToThirty;
            }else{
                tl_arr_cspm_twenty_thirty[i] = 0
            }

            if(data.matches[i].participants[0].timeline.creepsPerMinDeltas.thirtyToEnd != undefined) {
                tl_arr_cspm_thirty_end[i] = data.matches[i].participants[0].timeline.creepsPerMinDeltas.thirtyToEnd;
            }else{
                tl_arr_cspm_thirty_end[i] = 0
            }

            tl_arr_xppm_zero_ten[i] = data.matches[i].participants[0].timeline.xpPerMinDeltas.zeroToTen;
            tl_arr_xppm_ten_twenty[i] = data.matches[i].participants[0].timeline.xpPerMinDeltas.tenToTwenty;

            if(data.matches[i].participants[0].timeline.xpPerMinDeltas.twentyToThirty != undefined) {
                tl_arr_xppm_twenty_thirty[i] = data.matches[i].participants[0].timeline.xpPerMinDeltas.twentyToThirty;
            }else{
                tl_arr_xppm_twenty_thirty[i] = 0;
            }

            if(data.matches[i].participants[0].timeline.xpPerMinDeltas.thirtyToEnd != undefined){
                tl_arr_xppm_thirty_end[i] = data.matches[i].participants[0].timeline.xpPerMinDeltas.thirtyToEnd;
            }else{
                tl_arr_xppm_thirty_end[i] = 0;
            }


            tl_arr_gpm_zero_ten[i] = data.matches[i].participants[0].timeline.goldPerMinDeltas.zeroToTen;
            tl_arr_gpm_ten_twenty[i] = data.matches[i].participants[0].timeline.goldPerMinDeltas.tenToTwenty;

            if(data.matches[i].participants[0].timeline.goldPerMinDeltas.twentyToThirty != undefined){
                tl_arr_gpm_twenty_thirty[i] = data.matches[i].participants[0].timeline.goldPerMinDeltas.twentyToThirty;
            }else{
                tl_arr_gpm_twenty_thirty[i] = 0;
            }

            if(data.matches[i].participants[0].timeline.goldPerMinDeltas.thirtyToEnd != undefined){
                tl_arr_gpm_thirty_end[i] = data.matches[i].participants[0].timeline.goldPerMinDeltas.thirtyToEnd;
            }else{
                tl_arr_gpm_thirty_end[i] = 0;
            }


            //v1.0.2

            csArray[i] = data.matches[i].participants[0].stats.minionsKilled;
            assistArray[i] = data.matches[i].participants[0].stats.assists;
            killArray[i] = data.matches[i].participants[0].stats.kills;
            gameTimeArray[i] = data.matches[i].matchDuration;
            championArray[i] = data.matches[i].participants[0].championId;
            deathArray[i] = data.matches[i].participants[0].stats.deaths;
            jungleCSArray[i] = data.matches[i].participants[0].stats.neutralMinionsKilledTeamJungle;
            counterJungleCSArray[i] = data.matches[i].participants[0].stats.neutralMinionsKilledEnemyJungle;
            roleArray[i] = data.matches[i].participants[0].timeline.role;
            laneArray[i] = data.matches[i].participants[0].timeline.lane;
            crowdControlArray[i] = data.matches[i].participants[0].stats.totalTimeCrowdControlDealt;

            switch (roleArray[i]) {
                case "DUO":
                case "SOLO":
                    //assumes top lane duo player or solo mid or solo top
                    calculateHmc(championNumber, 1.33, 1, 0.5, 0.06, 0.11, 0.17, 5, 0.5, 4, 0.5, 0.16, 0.65, 2, 1.25, 3, 1.5, 1, 0.9, 0.8, 0.7, 1, 1.1, 1.1, 1.1, 1, 1.1, 1.2, 1.3,  i);
                    break;
                case "DUO_CARRY":
                    //assumes bot lane adc
                    calculateHmc(championNumber, 1.33, 1, 0.5, 0.06, 0.11, 0.17, 5, 0.5, 4, 0.5, 0.16, 0.65, 2, 1.25, 3, 2, 1, 0.9, 0.8, 0.7, 0.8, 0.8, 0.8, 0.8, 1, 1.1, 1.2, 1.3, i);
                    break;
                case "DUO_SUPPORT":
                    //assumes bot lane support
                    calculateHmc(championNumber, 1.33, 1, 0.75, 0.06, 0.11, 0.17, 0.5, 5, 4, 0.5, 0.16, 0.65, 2, 1.25, 0.25, 3.5, 0.1, 0.1, 0.1, 0.1, 0.8, 0.8, 0.8, 0.8, 0.3, 0.4, 0.5, 0.6, i);
                    break;
                case "NONE":
                    //assumes jungle, check lane
                    calculateHmc(championNumber, 1.33, 1, 0.5, 0.06, 0.11, 0.17, 2, 2.5, 4, 0.5, 0.16, 0.65, 2, 1.25, 1.5, 1.5, 0.6, 0.5, 0.4, 0.3, 1, 0.9, 0.8, 0.7, 1, 0.9, 0.8, 0.7, i);
                    break;
            }
        // console.log("loop worked for iteration " + i);
        }
    }
});


function calculateHmc(cNum, aF,bF,cF,dF,eF,fF,gF,hF,iF,kF,lF,mF,nF,oF,pF,qF,rF,sF,tF,uF,vF,wF,xF,yF,zF,aaF,bbF,ccF, n) {

//aF = first blood
//bF = kills
//cF = assists
//dF = creeps slain
//eF = jungle creeps slain
//fF = counter jungle creeps slain
//gF = gold earned
//hF = cc dealt in seconds
//iF = deaths
//jF = neutral monster kills
//kF = tower kills
//lF = inhibitor kills
//mF = first tower kill
//nF = first inhib kill
//oF = damage taken
//pF = damage dealt
//qF = healing dealt

//rF = creeps slain per minute, time = 0min to 10min
//sF = creeps slain per minute, time = 10min to 20min
//tF = creeps slain per minute, time = 20min to 30min
//uF = creeps slain per minute, time = 30min to end

//vF = xp gain per minute, time = 0min to 10min
//wF = xp gain per minute, time = 10min to 20min
//xF = xp gain per minute, time = 20min to 30min
//yF = xp gain per minute, time = 30min to end

//zF = gold gain per minute, time = 0min to 10 min
//aaF = gold gain per minute, time = 10min to 20 min
//bbF = gold gain per minute, time = 20min to 30 min
//ccF = gold gain per minute, time = 30min to end


var pvpFactor = (
    ((aF * firstBloodArray[n]) +                                        // PVP FACTOR CONSISTS OF ((FIRST BLOOD KILL + NORMAL KILLS + ASSISTS) / (DEATHS + 1))/(GAMETIME / 60sec)
     (bF * killArray[n]) +
     (cF * assistArray[n])) /
     (iF * (deathArray[n] + 1)))/(gameTimeArray[n] / 3600);

pvpFactor = pvpFactor.toFixed(2);
pvpFactorArray.push(pvpFactor);
// console.log(pvpFactorArray);

var pveFactor =                                                         // PVE FACTOR CONSISTS OF 3 FACTORS WITHIN ITSELF, ADDED TOGETHER, SO, (FACTOR 1 + FACTOR 2 + FACTOR 3) = pveFactor.
    ((dF * csArray[n]) +
    (eF * jungleCSArray[n]) +                                           // FACTOR 1: MINIONS KILLED + JUNGLE MINIONS KILLED + COUNTERJUNGLE MINIONS KILLED, ALL DIVIDED BY GAMETIME IN UNITS: MINUTES ***NEEDS A SCALING FACTOR***
    (fF * counterJungleCSArray[n])) / ((gameTimeArray[n]) / 60) +
                                                                        // +
    ((rF * tl_arr_cspm_zero_ten[n]) +
    (sF * tl_arr_cspm_ten_twenty[n]) +                                  // FACTOR 2: MINIONS KILLED PER MINUTE @ 0-10, 10-20, 20-30, 30-end ALL ADDED TOGETHER ***NEEDS A SCALING FACTOR***
    (tF * tl_arr_cspm_twenty_thirty[n]) +
    (uF * tl_arr_cspm_thirty_end[n])) +
                                                                        // +
    ((vF * tl_arr_xppm_zero_ten[n]) +
     (wF * tl_arr_xppm_ten_twenty[n]) +                                    // FACTOR 3: EXPERIENCE GAINED PER MINUTE @ 0-10, 10-20, 20-30, 30-end ALL ADDED TOGETHER ***NEEDS A SCALING FACTOR***
     (xF * tl_arr_xppm_twenty_thirty[n]) +
     (yF * tl_arr_xppm_thirty_end[n]));

pveFactor = pveFactor.toFixed(2);
pveFactorArray.push(pveFactor);
// console.log(pveFactorArray);

var auxFactor =
    ((hF * crowdControlArray[n]) +                                      // AUX FACTOR CONSISTS OF (CC DEALT + DAMAGE DEALT + HEALING DEALT) / DAMAGE TAKEN / GAMETIME(min)
     (pF * damageDealtArray[n]) +
     (qF * healingDealtArray[n])) +

    ((kF * towerArray[n]) +
    (lF * inhibitorArray[n]) +
    (mF * firstTowerArray[n]) +
    (nF * firstInhibitorArray[n])) +

    ((zF * tl_arr_gpm_zero_ten[n]) +
    (aaF * tl_arr_gpm_ten_twenty[n]) +
    (bbF * tl_arr_gpm_twenty_thirty[n]) +
    (ccF * tl_arr_gpm_thirty_end[n])) /

    ((oF * damageTakenArray[n]) /
    (gameTimeArray[n] / 60));


auxFactor = auxFactor.toFixed(2);
auxFactorArray.push(auxFactor);
// console.log(auxFactorArray);

var rawHMC = (1000 * pvpFactor) + (2 * pveFactor) + (0.01 * auxFactor);
hmcArray.push(rawHMC);
// console.log(hmcArray);

if(hmcArray.length == 5){

    psdb_pvp.push([[cNum], pvpFactorArray]);
    //console.log("PVP FACTOR ARRAY")
    //console.log(pvpFactorArray);
    psdb_pve.push([[cNum], pveFactorArray]);
    //console.log("PVE FACTOR ARRAY")
    //console.log(pveFactorArray);
    psdb_aux.push([[cNum], auxFactorArray]);
    //console.log("AUX FACTOR ARRAY")
    //console.log(auxFactorArray);
    psdb_hmc.push([[cNum], hmcArray]);


    //console.log(psdb_pvp);
    //console.log(psdb_pve);
    //console.log(psdb_aux);
    console.log(psdb_hmc);

    pvpFactorArray = [];
    pveFactorArray = [];
    auxFactorArray = [];
    hmcArray = [];

}






}

这是我的控制台输出,用于成功输入数组。在这里你可以看到它在counter == 9 时获取并推送一个数组。:

这是一个示例,说明它出于某种随机原因跳过此操作:

这两次运行之间没有代码更改。我所做的只是刷新页面并再次单击sendButton

我意识到有很多东西需要吸收,但我不想简化我的代码并意外排除可能是问题的东西,因为我真的不知道为什么会发生这种情况。

非常感谢您的帮助!

【问题讨论】:

  • 您必须等待getScore 完成才能更新计数器,尝试使用回调或承诺
  • 那里有很多代码需要查看,但我建议的一件事是使用 setTimeout 而不是 setInterval。然而,不是仅仅将 setTimeouts 放在一个 for 循环中,而是在执行所有其他数据处理功能之后,让 setTimeout 的回调和 ajax 调用创建下一个。这样,各种超时/ajax 函数就不可能重叠。这样做的缺点是您可能会发现 ajax 调用之间的时间不是 100% 正常的,但我认为它对于您的目的来说已经足够接近了。
  • @charlietfl 我相信我确实展示了间隔循环和 ajax 调用,只需查看数组下方。
  • @RodrigoAssis 谢谢你,我会看看这些是什么。保罗也谢谢你,我需要看看回调是什么。
  • 当函数不接受任何参数时,为什么要将counter 作为附加参数传递给setInterval

标签: javascript jquery ajax loops settimeout


【解决方案1】:

虽然这绝不是一个完整的答案,但这里有一个如何使用回调/setTimeout 来防止冲突的示例。在这个例子中,我们发送我们的 ajax 请求,等到收到成功的响应,处理数据,然后我们才设置超时以调用下一个 ajax 请求。

function getScore(summonerId, championNumber,  region, summonerName) {
    $.ajax({
       dataType: "json",
       type: 'GET',
       url: 'https://' + region + '.api.pvp.net/api/lol/' + region + '/v2.2/matchhistory/' + summonerId + '?championIds=' + championNumber + '&queueType=NORMAL_5x5_BLIND,NORMAL_5x5_DRAFT,RANKED_SOLO_5x5,RANKED_PREMADE_5x5,NORMAL_5x5_DRAFT,RANKED_TEAM_5x5&beginIndex=0&endIndex=5&api_key=***********************',
       success: function (data, state) {
           //process my data here
           //after processing my data, get my new parameters (using counter?)
           //and call getScore again
           setTimeout(function(){ getScore(my, incremented, parameters, here); }, 1050); //call getScore in 1.05s
       }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-23
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    相关资源
    最近更新 更多