Reputation: 1533
I have two checkboxes on selection of each one will raise a ajax request in order to get response from server. I need to call a method when there is atleast 2 seconds gap after the last request is made. Any idea? This means i do not want to call the methods when checkboxes are clicked continously for less than 2 seconds gap.
Upvotes: 0
Views: 232
Reputation: 5
var timeOut=0;
$(".selector").on('change',function(){
if(timeOut == 0)
{
timeOut=2; //change timeOut variable to "2" to be used in if condition above
//your ajax request code ;
setTimeout(function(){timeOut=0},2000); // changing back timeOut to 0 after 2 sec.
}
});
Upvotes: 1
Reputation: 3183
If it is your server, which you call with ajax, you could set up a lock on on the server for the specific client (e.g. using a mysql table) with the pair of identification & time of the call. The next time a call is made, you check the table for recent calls. When a call is found and older than 2 seconds: delete it and proceed. I could also think of a cookie solution, but stuff like this should be double checked on the server side always, since local code can be manipulated.
Upvotes: 0
Reputation: 490253
Set a timeout that will be activated in 2 seconds, and cancel it and restart it whenever someone clicks another checkbox.
var timeout;
var checkboxClickHandler = function() {
clearTimeout(timeout);
var timeout = setTimeout(function() {
// Your logic.
}, 2e3);
};
Upvotes: 2