我有点困惑,我从其他地方读到超时/间隔是使 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/