- I have an input text which is used to filter and sort the contents of a select dropdown.
- The filtration/selection function
filterSort()
is called onkeyup
on the input text.
Code
$(inputTextField).keyup(function()
{
//lot of logic to filter the options of a select dropdown开发者_StackOverflow社区 and sort them based on the text of inputTextField
});
Problem
The filtration/sorting logic is working fine now. But I realized that while a user is typing, there are multiple threads executing the code insidefilterSort()
. So, I want to stop execution of the code inside the keyup()
if another keyup()
has happened, because there is no need to continue with an older thread as its results will be anyway discarded. Never encountered such a situation. How do I do this?
I am not yet sure if that is functionally causing any problem, I think I am getting the correct filtered+sorted results in the end.
A solution would be to delay the filtering operation with setTimeout() and reset the timer every time the user presses a key. jQuery's data() method can be used to keep track of the timer identifier:
$(inputTextField).keyup(function() {
var $this = $(this);
var timer = $this.data("timer");
if (timer) {
window.clearTimeout(timer);
}
$this.data("timer", window.setTimeout(function() {
// Lots of logic to filter and sort the options...
}, 250));
});
精彩评论