Debounce
If we have a scenario where there are multiple consecutive requests and
we have to handle them, for eg If we want to save a textbox inputs
while writing, then on the hitting of each keystroke we can we can queue the message
for a certain amount of time and save it.
Debouncing enforces that a function not is called again until a certain
the amount of time has passed without it being called.
As in "execute this function only if 100 milliseconds have passed without it
being called.
Jquery Example
$(window).on('resize', _.debounce(function() {
// Do expensive things
}, 100));
Throttle
If we have a scenario where we want in a certain amount of time only our request should fire
max this many time.
Throttling enforces a maximum number of times a function can be called over
time. As in "execute this function at most once every 500 milliseconds."
Jquery Example
$("body").on('scroll', _.throttle(function() {
// Do expensive things
}, 100));
Popular Use cases:
If we have a scenario where there are multiple consecutive requests and
we have to handle them, for eg If we want to save a textbox inputs
while writing, then on the hitting of each keystroke we can we can queue the message
for a certain amount of time and save it.
Debouncing enforces that a function not is called again until a certain
the amount of time has passed without it being called.
As in "execute this function only if 100 milliseconds have passed without it
being called.
Jquery Example
$(window).on('resize', _.debounce(function() {
// Do expensive things
}, 100));
Throttle
If we have a scenario where we want in a certain amount of time only our request should fire
max this many time.
Throttling enforces a maximum number of times a function can be called over
time. As in "execute this function at most once every 500 milliseconds."
Jquery Example
$("body").on('scroll', _.throttle(function() {
// Do expensive things
}, 100));
Popular Use cases:
- Wait until the user stops resizing the window
- Don't fire an ajax event until the user stops typing
- Measure the scroll position of the page and respond at most every 50ms
- Ensure good performance as you drag elements around in an app
No comments:
Post a Comment