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?
-
1You can use setTimeout(). If you want anything more specific you'll have to show us your code and what you have tried.– Jay BlanchardCommented Feb 11, 2013 at 14:01
5 Answers
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:
-
1
-
@dfsq that doesn't work if there's no button. Like in my case.– LoolooiiCommented Feb 11, 2013 at 14:18
-
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() {});
}
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.