How to throttle callback of jQuery event?

后端 未结 4 1026
闹比i
闹比i 2020-12-31 22:47

Ok, so I do search like in google, you type text in input and it gives you entries instantly. But I don\'t like that. I use something like that $(\"TEXTINPUT\").keyup(

4条回答
  •  猫巷女王i
    2020-12-31 23:24

    This function will act somewhat like underscore.js, but without the extra dependency. It'll also pass the scope and arguments it's called with to the wrapped function. Unlike YoannM's answer, this returns a self-contained callback that uses no external variables (EG, use as many times as you want).

    function throttle (func, wait) {
        return function() {
            var that = this,
                args = [].slice(arguments);
    
            clearTimeout(func._throttleTimeout);
    
            func._throttleTimeout = setTimeout(function() {
                func.apply(that, args);
            }, wait);
        };
    }
    

    And usage would be nearly identical to that of the underscore.js library.

    $('input').on('input keyup', throttle(function() {
        // ...
    }, 100));
    

提交回复
热议问题