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

前端 未结 27 2639
半阙折子戏
半阙折子戏 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条回答
  •  我寻月下人不归
    2020-11-22 00:00

    Here is a suggestion I have written that takes care of multiple input in your form.

    This function gets the Object of the input field, put in your code

    function fieldKeyup(obj){
        //  what you want this to do
    
    } // fieldKeyup
    

    This is the actual delayCall function, takes care of multiple input fields

    function delayCall(obj,ms,fn){
        return $(obj).each(function(){
        if ( typeof this.timer == 'undefined' ) {
           // Define an array to keep track of all fields needed delays
           // This is in order to make this a multiple delay handling     
              function
            this.timer = new Array();
        }
        var obj = this;
        if (this.timer[obj.id]){
            clearTimeout(this.timer[obj.id]);
            delete(this.timer[obj.id]);
        }
    
        this.timer[obj.id] = setTimeout(function(){
            fn(obj);}, ms);
        });
    }; // delayCall
    

    Usage:

    $("#username").on("keyup",function(){
        delayCall($(this),500,fieldKeyup);
    });
    

提交回复
热议问题