javascriptjqueryfunctionjquery-click-event

JavaScript click event timer going fast


You can check whole of my codes in github pages function with this Link

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.

$(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. Timer function will called again again so the counter goes faster. Not each 1 second. But I don't have any idea of this.


Solution

  • 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);
    }