How can I prevent an AJAX request if it's within 5 seconds of the previous request?

I have a comment field that allows the user to leave comments by pressing enter. It does it with a query AJAX

(jQuery). Is there a good way to prevent an event from burning if it is within 5 seconds after the previous comment and show the message? Or does it have to be handled server side?

+3


source to share


5 answers


This should definitely be handled on the server as well, because the javascript restrictions can be bypassed. But a javascript solution can save traffic and time:



var last_req = 0;
var limit = 5000; //miliseconds
function send_comment() {
  var time = new Date().getTime();
  if(time-last_req<limit)  {
    alert("Wait please");
    return false;
  }
  last_req = time;
  $.get("comment.php", {/*data*/}, function() {});
}

      

+1


source


Depending on your use case, you can use throttle

either debounce

:

http://benalman.com/code/projects/jquery-throttle-debounce/examples/debounce/



Or check out this post:

fooobar.com/questions/585755 / ...

+5


source


This can be done simply with a boolean flag ...

// declare this globally at the top of your script
var allowAjax = true;


// this would be in some event handler (on enter keypress, for example)
if (allowAjax) {
    $.ajax({
        ...
        ...
    });
} else {
    // show message saying to wait
}

allowAjax = false;

setTimeout(function() {
    allowAjax = true;
}, 5000);

      

+1


source


I would use this:

if(timerStarted){
    window.clearTimeout(timeout);
}
timerStarted = true;
timeout = window.setTimeout(function(){
    timerStarted = false;
    // ajax call
, 5000}

      

+1


source


This might help you what you want to do: http://jeykeu.wordpress.com/2012/03/09/jquery-prevent-multiple-ajax-requests/

You need to modify it a little to add a timer and use it for testing to see if a new request is possible.

0


source







All Articles