简体   繁体   中英

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?

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

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() {});
}

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

I would use this :

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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