I haven't published a new article for a long time. I heard that everyone loves to watch animation, so come here all night
Throttling and Stabilization
This is a common question in front-end interviews, and you may be asked to write it by hand on the spot. 节流
and 防抖
are used to control the calling frequency of certain functions. For example, resize
when we are in a window, we may need to request more content from the server to fill the viewable area because the viewable area becomes larger. But in the process of increasing the visible area, resize
the event will be triggered multiple times...it is not necessary to request once every time it is triggered... then it needs to be 节流防抖
controlled
Why throttling.gif
function resize(e) {
console.log("窗口大小改变了");
}
window.addEventListener('resize', resize);
throttle
When resize
the event is triggered, it is not allowed to be triggered again within the specified time. If you encounter handwriting during the interview, you may ask about several implementation methods
1. Timestamp version
Throttle Timestamp Version.gif
function throttle(func, delay) {
var last = 0;
return function () {
var now = Date.now();
if (now >= delay + last) {
func.apply(this, arguments);
last = now;
} else {
console.log("距离上次调用的时间差不满足要求哦");
}
}
}
Throttling Timestamp Edition Execution.gif
2. Timer version
function throttle(func, delay) {
var timer = null;
return function () {
if (!timer) {
func.apply(this, arguments);
timer = setTimeout(() => {
timer = null;
}, delay);
} else {
console.log("上一个定时器尚未完成");
}
}
}
Throttle timer version execution.gif
Regardless of the above-mentioned writing methods, throttling means that the function is called multiple times within a period of time, and only the first time is valid.
So 节流
it's like a gatekeeper, it only lets one person in every once in a while
Anti-shake (debounce)
防抖
The difference 节流
is that when the function is called multiple times within a period of time, only the last call is valid.
function debounce(func, delay) {
var timeout;
return function() {
clearTimeout(timeout);
timeout = setTimeout(()=>{
func.apply(this, arguments);
}, delay);
}
}
So 防抖
it's like the undecided area in a PK game, the next undecided person will kick out the previous undecided person
Have you learned it? Those who like and bookmark must pass every exam, get promoted and raise their salary, and reach the pinnacle of life
I heard that if you follow Dashuai Laoyuan on Xiaopozhan, you can see more animation video tutorials at the first time