⬆️ ⬇️

Optimization micropatterns in Javascript: debouncing and throttling function decorators

Function decorators allow you to add additional behavior to the function without changing it. The signature of the original and decorated functions are completely the same.





Debouncing



If literally translated - "the elimination of bounce." Such a decorator allows you to turn several function calls for a certain time into one call, and the delay begins to re-count with each new call attempt. Two options are possible:

  1. A real call occurs only if more than or equal to the delay has passed since the last attempt.
  2. The actual call occurs immediately, and all other call attempts are ignored until a time longer or equal to the delay counted from the time of the last attempt passes.

Using



debouncedFn = $.debounce( fn , timeout , [ invokeAsap ], [ context ]);



Usage example



For example, you have suggest. To send requests to the server for each keyup wasteful and unnecessary. You can decorate the handler so that it works only after the user stops pressing keys, say, for 300 milliseconds:

function onKeyUp() { ... };



$( 'input[name=suggest]' ).keyup($.debounce(onKeyUp, 300));




* This source code was highlighted with Source Code Highlighter .


Or you have one handler for several events, and it is necessary that if for some time both events occur, the handler will only work on the last event that occurred:

$( 'input' ).bind( 'keyup blur' , $.debounce(process, 300));



* This source code was highlighted with Source Code Highlighter .


Throttling



This decorator allows you to "slow down" the function - the function will be performed no more than once in a specified period, even if it is called many times during this period. Those. all intermediate calls will be ignored.



Using



throttledFn = $.throttle( fn , period , [ context ]);

Usage example



For example, on the resize window (or, say, on the mousemove ), you have some kind of heavy handler. You can “slow down” it:

$(window).resize($.throttle(doComplexomputation, 300));
As a result, the function will be executed no more than once every 300 milliseconds.

')

My implementations of these decorators in the form of a jQuery plugin can be downloaded from code.google .



Ps. Inspired by the book “ Professional JavaScript for Web Developers, 2nd Edition ” by Nicholas Zakas, although in it he confuses debounce and throttle , calling the first the second. Ajaxian also raised this topic .

Source: https://habr.com/ru/post/60957/



All Articles