How to throttle callback of jQuery event?

后端 未结 4 1013
闹比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: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...

提交回复
热议问题