[英]JavaScript click event timer going fast
You can check whole of my codes in github pages function with this Link 您可以使用此链接在github页面函数中检查我的全部代码
I make the timer function and it's look like this. 我使计时器功能,它看起来像这样。
function timer() {
seconds += 1;
$(".timer").html(seconds);
timerPrint = setTimeout(timer, 1000);
console.log(seconds);
}
Every one second It will count the one second. 每隔一秒钟就会计算一秒钟。
And I put it in the click event function because I want to make it when I click the li element the game will be start and Timer goes up. 我将它放在click事件函数中是因为当我单击li元素时,我想创建它,游戏将开始并且Timer计时到。
$(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);
}
}
})
});
But the problem is that when I click each li element. 但是问题是当我单击每个li元素时。 Timer function will called again again so the counter goes faster.
定时器功能将再次被调用,因此计数器运行更快。 Not each 1 second.
并非每个1秒。 But I don't have any idea of this.
但是我对此一无所知。
Just check to see if timer already exists, and if it does, simply return: 只需检查计时器是否已经存在,如果存在,只需返回:
function timer() {
if (timerPrint) {
return;
}
seconds += 1;
$(".timer").html(seconds);
timerPrint = setTimeout(timer, 1000);
console.log(seconds);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.