防抖
如果一个事件在短时间内连续触发,则只去执行最后一次。 控制频率
- 实现方式:每次触发事件时设置一个延迟调用方法,并且取消之前的延时调用方法
- 缺点:如果事件在规定的时间间隔内被不断的触发,则调用方法会被不断的延迟
-
/** * @desc 函数防抖 * @param func 回调函数 * @param delay 延迟执行毫秒数 */ function _debounce(func, delay) { let timer; // 定时器return function () { let context = this; // 记录 this 值,防止在回调函数中丢失let args = arguments; // 函数参数// 标识是否立即执行let isImmediately = !timer;//如果定时器存在,则清除定时器(如果没有,也没必要进行处理)timer ? clearTimeout(timer) : null; timer = setTimeout(() => { timer = null;}, delay);// isImmediately 为 true 则 执行函数(即首次触发事件)isImmediately ? func.apply(context, args) : null;} }
节流
使一个函数在固定时间内只执行一次。控制次数
- 实现方式:每次触发事件时,如果当前有等待执行的延时函数,则直接return
-
//节流throttle代码: function throttle(fn,delay) {let canRun = true; // 通过闭包保存一个标记return function () {// 在函数开头判断标记是否为true,不为true则returnif (!canRun) return;// 立即设置为falsecanRun = 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));