How to delay the .keyup() handler until the user stops typing?

前端 未结 27 2571
半阙折子戏
半阙折子戏 2020-11-21 23:32

I’ve got a search field. Right now it searches for every keyup. So if someone types “Windows”, it will make a search with AJAX for every keyup: “W”, “Wi”, “Win”, “Wind”, “Wi

27条回答
  •  -上瘾入骨i
    2020-11-22 00:20

    Based on the answer of CMS, I made this :

    Put the code below after include jQuery :

    /*
     * delayKeyup
     * http://code.azerti.net/javascript/jquery/delaykeyup.htm
     * Inspired by CMS in this post : http://stackoverflow.com/questions/1909441/jquery-keyup-delay
     * Written by Gaten
     * Exemple : $("#input").delayKeyup(function(){ alert("5 secondes passed from the last event keyup."); }, 5000);
     */
    (function ($) {
        $.fn.delayKeyup = function(callback, ms){
            var timer = 0;
            $(this).keyup(function(){                   
                clearTimeout (timer);
                timer = setTimeout(callback, ms);
            });
            return $(this);
        };
    })(jQuery);
    

    And simply use like this :

    $('#input').delayKeyup(function(){ alert("5 secondes passed from the last event keyup."); }, 5000);
    

    Careful : the $(this) variable in the function passed as a parameter does not match input

提交回复
热议问题