Your iTimeoutID
is a local variable to the .on()
event handler function and thus it's destroyed each time that function completes and recreated the next time. Move it out of that scope to a higher level or to the global level so it can survive from one event to the next.
You can do it like this;
var iTimeoutID = null;
$(document).on('keyup', '#filter_query', function (event) {
var iTypingDelay = 800,
sFilterVal = $.trim($('#filter_query').val()),
sFilterCat = $('#filter_catagory').val(),
sFilterCol = $('#filter_col').val();
if (iTimeoutID) {
clearTimeout(iTimeoutID);
iTimeoutID = null;
}
if (sFilterVal !== "") {
iTimeoutID = setTimeout(function() {
iTimeoutID = null;
searchFunction();
}, iTypingDelay);
}
});
If you want to avoid global variables or you have more than one of these, you can use jQuery's .data()
to store the timer id on the object like this:
$(document).on('keyup', '#filter_query', function (event) {
var self = $(this);
var iTimeoutID = self.data("timerID") || null;
var iTypingDelay = 800,
sFilterVal = $.trim($('#filter_query').val()),
sFilterCat = $('#filter_catagory').val(),
sFilterCol = $('#filter_col').val();
if (iTimeoutID) {
clearTimeout(iTimeoutID);
iTimeoutID = null;
}
if (sFilterVal !== "") {
iTimeoutID = setTimeout(function() {
self.data("timerID", null);
searchFunction();
}, iTypingDelay);
}
self.data("timerID", iTimeoutID);
});
Here's one other version that uses a self-executing function to act as a shell for some variables that can last across the event handlers without being global:
(function() () {
var iTimeoutID = null;
$(document).on('keyup', '#filter_query', function (event) {
var iTypingDelay = 800,
sFilterVal = $.trim($('#filter_query').val()),
sFilterCat = $('#filter_catagory').val(),
sFilterCol = $('#filter_col').val();
if (iTimeoutID) {
clearTimeout(iTimeoutID);
iTimeoutID = null;
}
if (sFilterVal !== "") {
iTimeoutID = setTimeout(function() {
iTimeoutID = null;
searchFunction();
}, iTypingDelay);
}
});
})();
If this was something quick and there was little chance of conflict with other code and there's only one object being served by the event handler, the first option is perfectly fine.
If the .on()
event handler served multiple objects and each needed to keep track of it's own state, the 2nd option is perfect for that.
If you don't have multiple objects on the same event handler, then the third option is the simplest way to keep from adding any new global variables.