Shake debounce decorator
Callback is triggered in the event n seconds, and then, if this has been triggered in n seconds, then re-timing.
function debounce(func, delay) { let isCooldown = false; return function() { if (isCooldown) return; func.apply(this, arguments); isCooldown = true; setTimeout(() => isCooldown = false, delay); }; }
Throttle throttle decorator
Within a specified unit of time, it can only be triggered once the function. If this unit within the time-triggered multiple functions take effect only once.
function throttle(func, delay) { let isThrottled = false, savedArgs, savedThis; function wrapper() { if (isThrottled) { // (2) savedArgs = arguments; savedThis = this; return; } func.apply(this, arguments); // (1) isThrottled = true; setTimeout(function() { isThrottled = false; // (3) if (savedArgs) { wrapper.apply(savedThis, savedArgs); savedArgs = savedThis = null; } }, delay); } return wrapper; }
2 by the difference between:
- Anti-shake function and a function to prevent the throttle all the time frequently trigger, but the principle is not the same between the two brothers.
- Image stabilization function is performed only once for a certain period of time, and the time to perform the function of throttling interval.
Scenario:
- debounce
- associative search searches, when the user continues to input values, using the anti-shake request to save resources.
- When the window resize trigger, and constantly adjust the size of the browser window will continue to trigger this event with image stabilization to let triggered only once.
- throttle
- Click the mouse constantly triggered, mousedown (trigger only once per unit time).
- Listen scroll events, such as whether the bottom of the slide automatically load more, with the throttle to judge.