Reputation: 426
I have some text boxes that uses AJAX and will process what the user types as they're typing. The problem is that the process that happens after they type is a pretty loaded one. Is there anyway that I can make the event wait 500 msec or so before it will process the event again? So let's say I type a
, and then 200ms after I type bsdke
. The event will only process a
coming in. Let's say I then type asdf
600ms after I typed a
. The event will then trigger and process absdkeasdf
because it has been 500ms after the last process.
Or even, is there a way I can make the event not become triggered until the previous event that was triggered has finished what it was doing?
Is it possible? Surely sticking a timeout function at the end isn't going to work, right?
$('#selection1-3-4-a, #selection1-3-4-b, #selection1-3-4-c, #selection1-3-4-d, #selection1-3-4-e, #selection1-3-4-f').on('input', function (e) {
var url = "/ex.php";
$.ajax ({
//......
});
Upvotes: 0
Views: 337
Reputation: 7469
It can get hard to tune the event so the users gets a nice experience and you don't flood the server with requests when using autocomplete functions.
I would do it this way: The event will wait X miliseconds to run itself. If the event is fired again, and the X miliseconds haven't passed, you reset the delay to 0.
Let's be cool and make a generic function to do this (couldn't test it, it might be broken):
function delayedEvent(eventHandler, delay) {
var lastTimeout = null;
return function () {
var that = this,
args= Array.prototype.slice.call(arguments).sort();
if (lastTimeout !== null)
window.clearTimeout(lastTimeout);
lastTimeout = window.setTimeout(function () {
eventHandler.apply(that, args);
}, delay);
};
}
$('... selector ...').on('event', delayedEvent(function () { ... your code ... }, 500));
Upvotes: 1
Reputation: 2945
I would recommend using a lock.
// global lock
var locked = false;
$('#selection1-3-4-a, #selection1-3-4-b, #selection1-3-4-c, #selection1-3-4-d, #selection1-3-4-e, #selection1-3-4-f').change(function (e)
{
if(!locked)
{
locked = true;
$.ajax(......) // ajax here
setTimeout(function(){locked = false;}, 500);
}
});
Upvotes: 0
Reputation: 66660
Use setTimeout:
var timer;
$('#selection1-3-4-a, #selection1-3-4-b, #selection1-3-4-c, #selection1-3-4-d, #selection1-3-4-e, #selection1-3-4-f').on('input', function (e) {
var url = "/ex.php";
clearTimeout(timer);
timer = setTimeout(function() {
$.ajax ({
//......
}, 500);
});
Upvotes: 0