Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Spamming of button to call function

Tags:

html

jquery

How can I prevent Spamming of button on calling a function?? like the user can only call the function every 1 sec on the button.

Is there a way doing it?? cause I tried setTimeout but it didnt works it still spamming BTW i used Jquery.

here is my code:

<button class="buttonUpdateStatus" id="idbuttonUpdateStatus" onclick="alertStatus()">Post Status</button>



 function alertStatus() {
        $('#doneStatus').hide();
        $('#loadingStatus').show();
  }
like image 298
rodolfo navalon Avatar asked Apr 12 '13 05:04

rodolfo navalon


2 Answers

You can lock (prevent the function logic from execution) the function in the following way:

var locked = false;
function alertStatus () {
    if (!locked) {
        locked = true;
        setTimeout(unlock, 1000);
        $('#doneStatus').hide();
        $('#loadingStatus').show();
    }
}

function unlock () {
    locked = false;
}

You can also disable the button such that the user cannot click it at all:

function alertStatus () {
    $('#idbuttonUpdateStatus').attr('disabled', 'disabled');
    setTimeout(enable, 1000);
    $('#doneStatus').hide();
    $('#loadingStatus').show();
}

function enable () {
    $('#idbuttonUpdateStatus').removeAttr('disabled');
}
like image 54
Konstantin Dinev Avatar answered Sep 27 '22 23:09

Konstantin Dinev


You cannot prevent the calling of a function in your web page. If hackers want to mess with the code in your page, they can.

If you want to block the frequent calling of an ajax function by a particular client, then you will have to do that on the server using techniques like client login, rate limiting, etc...


If you want to just prevent a normal mouse click from pressing the button more than once within a given time period, that's pretty easy. You just disable the button when it is pressed and only enable it again some time later.

like image 30
jfriend00 Avatar answered Sep 27 '22 23:09

jfriend00