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?
Asked
Active
Viewed 352 times
3

Loolooii
- 8,588
- 14
- 66
- 90
-
1You can use setTimeout(). If you want anything more specific you'll have to show us your code and what you have tried. – Jay Blanchard Feb 11 '13 at 14:01
5 Answers
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:

Community
- 1
- 1

Stijn Geukens
- 15,454
- 8
- 66
- 101
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() {});
}

Stijn Geukens
- 15,454
- 8
- 66
- 101

Tomáš Zato
- 50,171
- 52
- 268
- 778
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);

Reinstate Monica Cellio
- 25,975
- 6
- 51
- 67
1
I would use this :
if(timerStarted){
window.clearTimeout(timeout);
}
timerStarted = true;
timeout = window.setTimeout(function(){
timerStarted = false;
// ajax call
, 5000}

andrei
- 2,934
- 2
- 23
- 36
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.

jpsnow72
- 965
- 2
- 15
- 45