Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaScript点击事件计时器运行得很快_Javascript_Jquery_Function_Jquery Click Event - Fatal编程技术网

JavaScript点击事件计时器运行得很快

JavaScript点击事件计时器运行得很快,javascript,jquery,function,jquery-click-event,Javascript,Jquery,Function,Jquery Click Event,您可以使用此函数在github pages函数中检查我的全部代码 我做了定时器功能,它是这样的 function timer() { seconds += 1; $(".timer").html(seconds); timerPrint = setTimeout(timer, 1000); console.log(seconds); } 每一秒它都会计算一秒 我把它放在click事件函数中,因为我想在我点击li元素时,游戏开始,计时器启动 $(document

您可以使用此函数在github pages函数中检查我的全部代码

我做了定时器功能,它是这样的

function timer() {

    seconds += 1;
    $(".timer").html(seconds);
    timerPrint = setTimeout(timer, 1000);
    console.log(seconds);
}
每一秒它都会计算一秒

我把它放在click事件函数中,因为我想在我点击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元素时。计时器功能将再次调用,以便计数器运行更快。不是每一秒。但我对此一无所知。

只要检查一下计时器是否已经存在,如果已经存在,只需返回:

function timer() {
    if (timerPrint) {
        return;
    }
    seconds += 1;
    $(".timer").html(seconds);
    timerPrint = setTimeout(timer, 1000);
    console.log(seconds);
}

为什么不在每次单击时重置计时器?您还可以查看
setInterval
函数。