从循环启动函数,但只能启动一次



好的,所以我正在为在线 4 人游戏制作大厅功能。一切都准备好了,当所有 4 名玩家加入大厅时,我想开始 10 秒的倒计时,让玩家点击客户端的接受匹配。(灵感来自CSGO( 我使用 ajax 从 php 文件调用和刷新大厅数据,因此实时统计信息会显示大厅中的人。 这循环往复,问题就出现了。我希望在所有 4 名玩家加入时调用倒计时函数,并在玩家离开时立即停止它,但随着父函数循环(使用 javascript 中的设置间隔(,它还会重复调用倒计时函数。 试过这个,但没有帮助。

function loadlobbymodule(x){
var spl = x.split(",");
var lid = spl[1];
$.ajax({
url: 'inc/fn/lobbyload.php?lid='+ lid,
success: function(data) {
var spl = data.split(",");
var p1 = spl[0];
var p2 = spl[1];
var p3 = spl[2];
var p4 = spl[3];
var pl = spl[4];
var pleft = 4 - pl;
var p1_i = spl[5];
var p2_i = spl[6];
var p3_i = spl[7];
var p4_i = spl[8];
if(p1!=''){
$('#slot1').html('<img src="../../img/' + p1_i +'" width="100px" height="100px"><Br><br>' + p1);
} else{
$('#slot1').html('');
}
if(p2!=''){
$('#slot2').html('<img src="../../img/' + p2_i +'" width="100px" height="100px"><Br><br>' + p2);
}else{
$('#slot2').html('');
}
if(p3!=''){
$('#slot3').html('<img src="../../img/' + p3_i +'" width="100px" height="100px"><Br><br>' + p3);
}else{
$('#slot3').html('');
}
if(p4!=''){
$('#slot4').html('<img src="../../img/' + p4_i +'" width="100px" height="100px"><br><br>' + p4);
}else{
$('#slot4').html('');
}
$('#slotl').html(pleft + ' players left to join.');
if(pl == 4){
var accept = 1;
} else{
var accept = 0;
}
//alert(accept + ' sent');
accepto(accept);
}
});
}
function accepto(x){
//alert(x + ' reached');
if (x == 1){
if (!timeleft){
timeleft = 10;
var downloadTimer = setInterval(function(){
timeleft--;
$('.h3').html('All players joined. Accept in ' + timeleft + ' seconds');
if(timeleft <= 0)
clearInterval(downloadTimer);
},1000);
}
} else {
$('.h3').html('Waiting for players to join');
}
}setInterval(function(){loadlobbymodule(loll)}, 500);

使计时器全局并继续检查活跃玩家

window.myGlobalTimer = yourTimer()
listening_PlayerThatLeave : ()=>{
clearTimeout(myGlobalTimer)
}
listening_AllPlayersIn : ()=>{
window.myGlobalTimer
}
/* dont keep making a new timeOut everytime , instead use the global var*/
function accepto(x){
//alert(x + ' reached');
if (x == 1){
if (!timeleft){
timeleft = 10;
//here
var downloadTimer = setInterval(function(){
timeleft--;
$('.h3').html('All players joined. Accept in ' + timeleft + ' seconds');
if(timeleft <= 0)
clearInterval(downloadTimer);
},1000);
}
} else {
$('.h3').html('Waiting for players to join');
}
}

最新更新