How to throttle callback of jQuery event?

后端 未结 4 991
闹比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条回答
  • 2020-12-31 23:04

    Here's how I usually approach it:

    $(function(){
      var tiTO, jqXHR;
      $('textinput').keyup(function(){
        if (tiTO) clearTimeout(tiTO);
        if (jqXHR && jqXHR.abort) jqXHR.abort();
        tiTO = setTimeout(function(){
          jqXHR = $.ajax({....});
          //Ajax call to PHP
        },2000);
      });
    });
    

    Each keyup resets the timeout, and aborts any active ajax.

    0 讨论(0)
  • 2020-12-31 23:17

    If you use the Underscore Library it's as simple as this:

    $("TEXTINPUT").keyup(_.throttle(function () {...}, 150));

    Docs from the Underscore site:

    throttle   _.throttle(function, wait)

    Returns a throttled version of the function, that, when invoked repeatedly, will only actually call the wrapped function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

    There is also the debounce function:

    debounce   _.debounce(function, wait)

    Calling a debounced function will postpone its execution until after wait milliseconds have elapsed since the last time the function was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized...

    0 讨论(0)
  • 2020-12-31 23:24

    Try :

    var time_out;
    $("TEXTINPUT").keyup(function(){
        clearTimeout(time_out);
        time_out = setTimeout(your_function, 500);
    }
    
    function your_function()
    {
        /*CHECK DATABASE*/
    }
    
    0 讨论(0)
  • 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));
    
    0 讨论(0)
提交回复
热议问题