javascript - 从 $.each 方法中调用 setTimeout/Interval?

标签 javascript jquery

我有点困惑,我从其他地方读到超时/间隔是使 Javascript 中的函数每 x 秒运行一次的最佳方式。我必须让我的函数每 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);
            }
        });
}

提前谢谢你。

最佳答案

这正是setInterval & clearInterval是为了。

所以除了 setTimeout,你还可以使用它:

var timer = setInterval(function() {

       get_match_details(h);

}, 1000);                              // for every second

当你想停止它时,使用:

clearInterval(timer);

关于javascript - 从 $.each 方法中调用 setTimeout/Interval?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21753176/

相关文章:

javascript - 如何不显示字符串中只出现一次的短语?

javascript - Angular : using transclude with ng-bind-html

添加类后 jQuery 单击事件不起作用

javascript - 具有多个提交按钮的 PHP 表单

jQuery 循环输入问题

javascript - 字符串匹配和不匹配的正则表达式问题

javascript - 如何在 0 :0 处停止 JavaScript 计时器

javascript - Promise.all() 中的 Promise 有时返回未定义/crawler-request 包nodejs

jquery 显示/隐藏和不透明度

javascript - Vue 元素内部迭代