Objective
Anti-shake, throttling is mainly used for frequent event triggering, such as mouse movement, changing window size. Lodash and other function libraries have corresponding APIs, _.debounce
_.throttle
.
Core technology: Closures.
Difference:
- Anti-shake, continuous trigger, first and last trigger valid
- Throttling, triggering only once (first time) over a period of time
This article is to prevent the chattering function as an example, detailed description.
Realize
Principle, the timer stores the state.
function debounce(fn, delay) { return function() { console.log(fn.timer, count2); let _this = this; let _args = arguments; fn.timer !== undefined && clearTimeout(fn.timer); fn.timer = setTimeout(function() { fn.apply(_this, _args); }, delay); }}// 替换debounce(oldFunction, delay)();
Improved, can be called in multiple places
/** * 防抖函数*/function debounce(fn, delay) { let timer; return function () { let _this = this; let _args = arguments; console.log(timer, count2) timer !== undefined && clearTimeout(timer); timer = setTimeout(function () { fn.apply(_this, _args); }, delay); }}var newFucntion = debounce(oldFunction, delay);// 替换newFunction();
My test connection, open the console view
Reference
Inspiration-Mint Weekly, with errors, for reference only
Reference Blog
Reference Demo
"Source" anti-shake and throttle source analysis