JavaScript 点击事件计时器走得很快
JavaScript click event timer going fast
您可以使用此 Link
在 github 页面功能中检查我的全部代码
我做了定时器功能,它看起来像这样。
function timer() {
seconds += 1;
$(".timer").html(seconds);
timerPrint = setTimeout(timer, 1000);
console.log(seconds);
}
每一秒算一秒
我把它放在点击事件函数中,因为我想当我点击 li 元素时,游戏就会开始,计时器会启动。
$(document).ready(function () {
let clickhold = [];
$('.card').click(function () {
timer();
$(this).addClass('disable');
// Push the card to compare each other
clickhold.push($(this).children('.fa').attr('class'));
console.log(clickhold);
// Card Open
$(this).addClass("open show");
if (clickhold.length == 2) {
// Call moves Function to count move and stars.
moves();
$('.card').addClass('disable');
if (clickhold[0] === clickhold[1]) {
$('.open.show').removeClass("open show").addClass("match");
console.log('matched');
clickhold = [];
$('.card').removeClass('disable');
} else {
console.log('not matched');
clickhold = [];
let ele = $('.card');
setTimeout(function () {
ele.removeClass("open show");
$('.card').removeClass('disable');
}, 1000);
}
}
})
});
但问题是,当我单击每个 li 元素时。定时器功能将再次调用,因此计数器走得更快。不是每 1 秒。但我对此一无所知。
只需检查计时器是否已经存在,如果存在,只需 return:
function timer() {
if (timerPrint) {
return;
}
seconds += 1;
$(".timer").html(seconds);
timerPrint = setTimeout(timer, 1000);
console.log(seconds);
}
您可以使用此 Link
在 github 页面功能中检查我的全部代码我做了定时器功能,它看起来像这样。
function timer() {
seconds += 1;
$(".timer").html(seconds);
timerPrint = setTimeout(timer, 1000);
console.log(seconds);
}
每一秒算一秒
我把它放在点击事件函数中,因为我想当我点击 li 元素时,游戏就会开始,计时器会启动。
$(document).ready(function () {
let clickhold = [];
$('.card').click(function () {
timer();
$(this).addClass('disable');
// Push the card to compare each other
clickhold.push($(this).children('.fa').attr('class'));
console.log(clickhold);
// Card Open
$(this).addClass("open show");
if (clickhold.length == 2) {
// Call moves Function to count move and stars.
moves();
$('.card').addClass('disable');
if (clickhold[0] === clickhold[1]) {
$('.open.show').removeClass("open show").addClass("match");
console.log('matched');
clickhold = [];
$('.card').removeClass('disable');
} else {
console.log('not matched');
clickhold = [];
let ele = $('.card');
setTimeout(function () {
ele.removeClass("open show");
$('.card').removeClass('disable');
}, 1000);
}
}
})
});
但问题是,当我单击每个 li 元素时。定时器功能将再次调用,因此计数器走得更快。不是每 1 秒。但我对此一无所知。
只需检查计时器是否已经存在,如果存在,只需 return:
function timer() {
if (timerPrint) {
return;
}
seconds += 1;
$(".timer").html(seconds);
timerPrint = setTimeout(timer, 1000);
console.log(seconds);
}