Jquery Run code 2 seconds after last keypress

前端 未结 2 981
Happy的楠姐
Happy的楠姐 2020-12-02 17:17

I am working on a auto search function for a site.

It uses ajax to query an api.

At the moment after 3 characters are entered it will search on every key pre

相关标签:
2条回答
  • 2020-12-02 18:09

    Almost the same except that timer is set only when conditions are met:

    <input id="search" type="text" />
    <script>
        var timer, value;
        $('#search').bind('keyup', function() {
            clearTimeout(timer);
            var str = $(this).val();
            if (str.length > 2 && value != str) {
                timer = setTimeout(function() {
                    value = str;
                    console.log('Perform search for: ', value);
                }, 2000);
            }
        });
    </script>
    
    0 讨论(0)
  • 2020-12-02 18:20

    The following function from Remy Sharp will do the trick:

    function throttle(f, delay){
        var timer = null;
        return function(){
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = window.setTimeout(function(){
                f.apply(context, args);
            },
            delay || 500);
        };
    }
    

    In the preceding code, f is the function you would like to throttle and delay is the number of milliseconds to wait after the last call (defaults to 500 if omitted). throttle returns a wrapper function that clears any existing timeouts from previous calls and then sets a timeout for delay milliseconds in the future to call f. A reference to the arguments of the returned function is used to call f with, ensuring f receives the arguments it is expecting.

    You should use it as follows:

    $('#search').keyup(throttle(function(){
        // do the search if criteria is met
    }));
    
    0 讨论(0)
提交回复
热议问题