Personally, I found debounce harder than a throttle .
How both functions help delay and reduce execution speed. Assuming you call the decorated functions returned by the throttle / debounce repeatedly ...
- Throttle : call the original function no more than once per specified period.
- Debounce : function-function is called after the caller stops calling the decorated function after a specified period.
I found that the last part of the debut is crucial to understanding the goal she is trying to achieve. I also found that the old version of _.debounce implementation helps to understand (kindly https://davidwalsh.name/function-debounce ).
// Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; };
A far-fetched metaphor, but perhaps it can also help.
You have a friend named Chatti who loves to chat with you through IM. Assuming that when she speaks, she sends a new message every 5 seconds, while the icon of your IM application bounces up and down, you can take ...
- Naive approach: check every message as it arrives. When your app icon bounces, check. This is not the most effective way, but you are always up to date.
- Throttle Approach: You check once every 5 minutes (when there are new ones). When a new message arrives, if you checked at any time in the last 5 minutes, ignore it. You save your time with this approach while still in a loop.
- Failsafe approach: you know Chatti, she breaks the whole story into pieces, sends them in one message after another. Wait for Chatti to finish the whole story: if she stops sending messages within 5 minutes, you can assume that she has finished, now you check everything.
Dapeng Li Feb 09 '16 at 11:17 2016-02-09 11:17
source share