简体   繁体   English

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

[英]JS - prevent a function from executing next time for a duration

I have a JS function. 我有一个JS函数。 I want it to be paused after it's first-time execution for 10 s, and after that time I want to resume it. 我希望它在第一次执行10秒后暂停,之后我想恢复它。

So, what I have done is- 所以,我所做的是 -

$( "#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'
                },
        });
    }
});

But it I not working perfectly. 但它我没有完美地工作。 It prevents the function executing second time permanently if I click multiple times. 如果我多次单击,它会阻止该功能永久执行第二次。

Is there any solution? 有什么解决方案吗?

Thanks for helping 谢谢你的帮助

How about keeping track of the last time the button was clicked and ensuring that 10s has elapsed before processing the next click? 如何跟踪上次点击按钮并确保在处理下一次点击之前已经过了10秒?

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'
                },
        });
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM