Complete high-frequency question bank warehouse address: github.com/hzfe/awesom…
The full frequency question bank reading address: febook.hzfe.org/
The throttle
1. Basic concepts
throttle(func, wait)
Func can be called at most once per wait millisecond.
2. Application scenarios
-
Real-time association of search box input.
-
Listen for scroll events to compute position information.
Flow chart of 3.
4. Write code
function throttle(func, wait) { let lastTime = 0; let timer = null; return function () { if (timer) { clearTimeout(timer); timer = null; } let self = this; let args = arguments; let nowTime = +new Date(); const remainWaitTime = wait - (nowTime - lastTime); if (remainWaitTime <= 0) { lastTime = nowTime; func.apply(self, args); } else { timer = setTimeout(function () { lastTime = +new Date(); func.apply(self, args); timer = null; }, remainWaitTime); }}; }Copy the code
To shake
1. Basic concepts
debounce(func, wait)
Delay the func call in milliseconds since the last trigger.
2. Application scenarios
-
Check whether the user name is occupied after entering the user name during registration.
-
Listen for resize events to calculate size information.
Flow chart of 3.
4. Write code
function debounce(func, wait) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
timer = null;
}
let self = this;
let args = arguments;
timer = setTimeout(function () {
func.apply(self, args);
timer = null;
}, wait);
};
}
Copy the code