Loolooii
Loolooii

Reputation: 9162

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

I have a comment box which lets a user post comment by pressing enter. It does this using an AJAX (jQuery) request. Is there a nice way to not let the event fire if it's within 5 seconds of the previous comment and show a message? Or should this be handled server side?

Upvotes: 3

Views: 395

Answers (5)

Tomáš Zato
Tomáš Zato

Reputation: 53129

This should be definitelly also handled on server, because javascript restrictions can be bypassed. But, the javascript solution can save some 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() {});
}

Upvotes: 1

andrei
andrei

Reputation: 2940

I would use this :

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

Upvotes: 1

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

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);

Upvotes: 1

jpsnow72
jpsnow72

Reputation: 995

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

You would have to modify it slightly to add a timer and use that to test to see if a new request is possible.

Upvotes: 0

Stijn Geukens
Stijn Geukens

Reputation: 15628

Depending on your use case you could use throttle or debounce:

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

Or have a look at this post:

https://stackoverflow.com/a/8056049/190596

Upvotes: 5

Related Questions