2

I have a JS function. I want it to be paused after it's first-time execution for 10s, and after that time I want to resume it.

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Abrar Jahin
  • 13,970
  • 24
  • 112
  • 161

1 Answers1

3

How about keeping track of the last time the button was clicked and ensuring that 10s has elapsed before processing the next click?

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'
                },
        });
    }
});
arcyqwerty
  • 10,325
  • 4
  • 47
  • 84