Cancelling method calls when the same method is called multiple time

后端 未结 3 697
梦如初夏
梦如初夏 2021-01-13 06:05

I think there\'s probably a name for what I\'m describing here, but I don\'t know it. So my first question would be to know the name of this technique.

Here\'s an ex

3条回答
  •  执笔经年
    2021-01-13 06:27

    What you need is called debouncing. You should check the jQuery Throttle/Debounce plugin (which is btw totally independent of jQuery except for using the same namespace). What you need is covered by the debounce part:

    Using jQuery throttle / debounce, you can pass a delay and function to $.debounce to get a new function, that when called repetitively, executes the original function just once per “bunch” of calls, effectively coalescing multiple sequential calls into a single execution at either the beginning or end.

    Underscore.js has the same method:

    _.debounce(function, wait, [immediate]) 
    

    Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it 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, and so on.

    // example: debounce layout calculation on window resize
    var lazyLayout = _.debounce(calculateLayout, 300);
    $(window).resize(lazyLayout);
    

    [Edit]

    I mistakenly read "Javascript" instead of Java. Actual Java solution was written by OP afterwards.

提交回复
热议问题