开发者

How to stop execution of current event handler thread when subsequent events simultaneously call the same handler?

开发者 https://www.devze.com 2023-03-24 06:59 出处:网络
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 on keyup on the input text.
  • 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 on keyup 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 inside filterSort(). 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));
});
0

精彩评论

暂无评论...
验证码 换一张
取 消