Event handling optimization
It must have happened to you while writing a form inline validator that you run into a problem. As you type it, the user-agent
keeps sending validation requests to the server. This way you might quickly pollute the network with spawning XHRs. Another sort of problem that you may be familiar with, is that some UI events ( touchmove
, mousemove
, scroll
, and resize
) are fired intensively and subscribed handlers may overload the main thread. These problems can be solved using one of two approaches known as debouncing and throttling. Both functions are available in third-party libraries such as Underscore and Lodash (_.debounce
and _.throttle
). However, they can be implemented with a little o
code and one doesn't need to depend on extra libraries for this functionality.
Debouncing
By debouncing, we ensure that a handler function is called once for a repeatedly emitted event:
/** * Invoke a given callback only after this function stops being called `wait` milliseconds...