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

前端 未结 27 2569
半阙折子戏
半阙折子戏 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:10

    If you want to search after the type is done use a global variable to hold the timeout returned from your setTimout call and cancel it with a clearTimeout if it hasn't yet happend so that it won't fire the timeout except on the last keyup event

    var globalTimeout = null;  
    $('#id').keyup(function(){
      if(globalTimeout != null) clearTimeout(globalTimeout);  
      globalTimeout =setTimeout(SearchFunc,200);  
    }   
    function SearchFunc(){  
      globalTimeout = null;  
      //ajax code
    }
    

    Or with an anonymous function :

    var globalTimeout = null;  
    $('#id').keyup(function() {
      if (globalTimeout != null) {
        clearTimeout(globalTimeout);
      }
      globalTimeout = setTimeout(function() {
        globalTimeout = null;  
    
        //ajax code
    
      }, 200);  
    }   
    
    0 讨论(0)
  • 2020-11-22 00:11

    This worked for me where I delay the search logic operation and make a check if the value is same as entered in text field. If value is same then I go ahead and perform the operation for the data related to search value.

    $('#searchText').on('keyup',function () {
        var searchValue = $(this).val();
        setTimeout(function(){
            if(searchValue == $('#searchText').val() && searchValue != null && searchValue != "") {
               // logic to fetch data based on searchValue
            }
            else if(searchValue == ''){
               // logic to load all the data
            }
        },300);
    });
    
    0 讨论(0)
  • 2020-11-22 00:11
    // Get an global variable isApiCallingInProgress
    
    //  check isApiCallingInProgress 
    if (!isApiCallingInProgress) {
    // set it to isApiCallingInProgress true
          isApiCallingInProgress = true;
    
          // set timeout
          setTimeout(() => {
             // Api call will go here
    
            // then set variable again as false
            isApiCallingInProgress = false;     
          }, 1000);
    }
    
    0 讨论(0)
  • 2020-11-22 00:13

    I'm surprised that nobody mention the problem with multiple input in CMS's very nice snipped.

    Basically, you would have to define delay variable individually for each input. Otherwise if sb put text to first input and quickly jump to other input and start typing, callback for the first one WON'T be called!

    See the code below I came with based on other answers:

    (function($) {
        /**
         * KeyUp with delay event setup
         * 
         * @link http://stackoverflow.com/questions/1909441/jquery-keyup-delay#answer-12581187
         * @param function callback
         * @param int ms
         */
        $.fn.delayKeyup = function(callback, ms){
                $(this).keyup(function( event ){
                    var srcEl = event.currentTarget;
                    if( srcEl.delayTimer )
                        clearTimeout (srcEl.delayTimer );
                    srcEl.delayTimer = setTimeout(function(){ callback( $(srcEl) ); }, ms);
                });
    
            return $(this);
        };
    })(jQuery);
    

    This solution keeps setTimeout reference within input's delayTimer variable. It also passes reference of element to callback as fazzyx suggested.

    Tested in IE6, 8(comp - 7), 8 and Opera 12.11.

    0 讨论(0)
  • 2020-11-22 00:13

    Use the bindWithDelay jQuery plugin:

    element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)
    
    0 讨论(0)
  • 2020-11-22 00:15
    var globalTimeout = null;  
    $('#search').keyup(function(){
      if(globalTimeout != null) clearTimeout(globalTimeout);  
      globalTimeout =setTimeout(SearchFunc,200);  
    });
    function SearchFunc(){  
      globalTimeout = null;  
      console.log('Search: '+$('#search').val());
      //ajax code
    };
    
    0 讨论(0)
提交回复
热议问题