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

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

    I use this small function for the same purpose, executing a function after the user has stopped typing for a specified amount of time or in events that fire at a high rate, like resize:

    function delay(callback, ms) {
      var timer = 0;
      return function() {
        var context = this, args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
          callback.apply(context, args);
        }, ms || 0);
      };
    }
    
    
    // Example usage:
    
    $('#input').keyup(delay(function (e) {
      console.log('Time elapsed!', this.value);
    }, 500));
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label for="input">Try it:
    <input id="input" type="text" placeholder="Type something here..."/>
    </label>

    How it works:

    The delay function will return a wrapped function that internally handles an individual timer, in each execution the timer is restarted with the time delay provided, if multiple executions occur before this time passes, the timer will just reset and start again.

    When the timer finally ends, the callback function is executed, passing the original context and arguments (in this example, the jQuery's event object, and the DOM element as this).

    UPDATE 2019-05-16

    I have re-implemented the function using ES5 and ES6 features for modern environments:

    function delay(fn, ms) {
      let timer = 0
      return function(...args) {
        clearTimeout(timer)
        timer = setTimeout(fn.bind(this, ...args), ms || 0)
      }
    }
    

    The implementation is covered with a set of tests.

    For something more sophisticated, give a look to the jQuery Typewatch plugin.

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

    This function extends the function from Gaten's answer a bit in order to get the element back:

    $.fn.delayKeyup = function(callback, ms){
        var timer = 0;
        var el = $(this);
        $(this).keyup(function(){                   
        clearTimeout (timer);
        timer = setTimeout(function(){
            callback(el)
            }, ms);
        });
        return $(this);
    };
    
    $('#input').delayKeyup(function(el){
        //alert(el.val());
        // Here I need the input element (value for ajax call) for further process
    },1000);
    

    http://jsfiddle.net/Us9bu/2/

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

    jQuery:

    var timeout = null;
    $('#input').keyup(function() {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
          console.log($(this).val());
      }, 1000);
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    <input type="text" id="input" placeholder="Type here..."/>

    Pure Javascript:

    let input = document.getElementById('input');
    let timeout = null;
    
    input.addEventListener('keyup', function (e) {
        clearTimeout(timeout);
        timeout = setTimeout(function () {
            console.log('Value:', input.value);
        }, 1000);
    });
    <input type="text" id="input" placeholder="Type here..."/>

    0 讨论(0)
  • 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

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

    Super simple approach, designed to run a function after a user has finished typing in a text field...

    <script type="text/javascript">
    $(document).ready(function(e) {
        var timeout;
        var delay = 2000;   // 2 seconds
    
        $('.text-input').keyup(function(e) {
            console.log("User started typing!");
            if(timeout) {
                clearTimeout(timeout);
            }
            timeout = setTimeout(function() {
                myFunction();
            }, delay);
        });
    
        function myFunction() {
            console.log("Executing function for user!");
        }
    });
    </script>
    
    <textarea name="text-input" class="text-input"></textarea>
    
    0 讨论(0)
  • 2020-11-22 00:21

    Another slight enhancement on CMS's answer. To easily allow for separate delays, you can use the following:

    function makeDelay(ms) {
        var timer = 0;
        return function(callback){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        };
    };
    

    If you want to reuse the same delay, just do

    var delay = makeDelay(250);
    $(selector1).on('keyup', function() {delay(someCallback);});
    $(selector2).on('keyup', function() {delay(someCallback);});
    

    If you want separate delays, you can do

    $(selector1).on('keyup', function() {makeDelay(250)(someCallback);});
    $(selector2).on('keyup', function() {makeDelay(250)(someCallback);});
    
    0 讨论(0)
提交回复
热议问题