concept:
Function debounce: After a high-frequency event is triggered, the function will only be executed once within n seconds. If the high-frequency event is triggered again within n seconds, the time will be recalculated.
Function throttling (throttle): High-frequency events trigger, but only execute once in n seconds, so throttling will dilute the execution frequency of the function.
Function throttling (throttle) and function debounce (debounce) are both to limit the execution frequency of the function to optimize the response speed caused by the high trigger frequency of the function that cannot keep up with the trigger frequency, resulting in delay, suspended animation or freeze phenomenon.
1. Function anti-shake (debounce)
Implementation method: set a delayed call method every time an event is triggered, and cancel the previous delayed call method
Disadvantage: If the event is continuously triggered within the specified time interval, the call method will be continuously delayed
//防抖debounce代码:
function debounce(fn,delay) {
var timeout = null; // 创建一个标记用来存放定时器的返回值
return function (e) {
// 每当用户输入的时候把前一个 setTimeout clear 掉
clearTimeout(timeout);
// 然后又创建一个新的 setTimeout, 这样就能保证interval 间隔内如果时间持续触发,就不会执行 fn 函数
timeout = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
// 处理函数
function handle() {
console.log('防抖:', Math.random());
}
//滚动事件
window.addEventListener('scroll', debounce(handle,500));
2. Function throttling (throttle)
Implementation method: every time an event is triggered, if there is currently a delay function waiting to be executed, return directly
//节流throttle代码:
function throttle(fn,delay) {
let canRun = true; // 通过闭包保存一个标记
return function () {
// 在函数开头判断标记是否为true,不为true则return
if (!canRun) return;
// 立即设置为false
canRun = false;
// 将外部传入的函数的执行放在setTimeout中
setTimeout(() => {
// 最后在setTimeout执行完毕后再把标记设置为true(关键)表示可以执行下一次循环了。
// 当定时器没有执行的时候标记永远是false,在开头被return掉
fn.apply(this, arguments);
canRun = true;
}, delay);
};
}
function sayHi(e) {
console.log('节流:', e.target.innerWidth, e.target.innerHeight);
}
window.addEventListener('resize', throttle(sayHi,500));