在一段时间内阻止函数下次执行

Prevent a function from executing next time for a duration

本文关键字:函数 下次 执行 一段时间      更新时间:2023-09-26

我有一个JS函数。我想让它在第一次执行后暂停10秒,之后我想恢复它。

那么,我所做的是:

$( "#button_yes,#button_no" ).click(function()
{
    if(counter)
    {
        console.log('Done');
        $.ajax(
        {
            url: baseURL+"add_votes",
            success: function(result)
            {
                counter=0;
                alert(result);
                setTimeout(check, 10000); //set a 10s  delay
                counter=1;
            },
            method: "POST",
            data:
                {
                    id : '1'
                },
        });
    }
});

但如果我不能完美地工作。如果我多次单击,它将永久防止函数执行第二次。

有解决办法吗?

如何跟踪最后一次单击按钮并确保在处理下一次单击之前已经过了10s ?

var lastClicked = 0;
$( "#button_yes,#button_no" ).click(function()
{
    var now = new Date();
    if(now - lastClicked > 10000)
    {
        lastClicked = now;
        console.log('Done');
        $.ajax(
        {
            url: baseURL+"add_votes",
            success: function(result)
            {
                alert(result);
            },
            method: "POST",
            data:
                {
                    id : '1'
                },
        });
    }
});