3

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?

1
  • 1
    You can use setTimeout(). If you want anything more specific you'll have to show us your code and what you have tried. Commented Feb 11, 2013 at 14:01

5 Answers 5

5

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

3
  • 1
    Or he can also just disable a button for 5 seconds.
    – dfsq
    Commented Feb 11, 2013 at 14:16
  • @dfsq that doesn't work if there's no button. Like in my case.
    – Loolooii
    Commented Feb 11, 2013 at 14:18
  • 1
    @Loolooii That's why I put the word or in front :)
    – dfsq
    Commented Feb 11, 2013 at 14:21
1

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

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

I would use this :

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.