js函数防抖和函数节流
1.函数防抖:如果一个事件被频繁触发多次,并且触发的时间间隔过短,则防抖函数可以使得对应的事件处理函数只执行最后触发的一次。 函数防抖可以把多个顺序的调用合并成一次。
应用场景:搜索输入框获取接口数据
// 声明防抖函数 function debounce(func, delay, scope) { let timer = null; // 一个闭包的函数 return function() { if (timer) { clearTimeout(time); } let context = scope || this; timer = setTimeout(function() { func.apply(context, arguments); }, delay); }; } // 调用方式 document.addEventListener( 'input', debounce(() => { // 获取请求数据 }, 1000), );
2.函数节流:如果一个事件被频繁触发多次,节流函数可以按照固定频率去执行对应的事件处理方法。 函数节流保证一个事件一定时间内只执行一次。
应用场景:按钮重复点击,滚动条重复滚动
// 声明节流函数 function throttle(func, threshold, scope) { let prevTime = Date.now(); return function() { let context = scope || this; let nowTime = Date.now(); if (nowTime - prevTime > threshold) { prevTime = nowTime; func.apply(context, arguments); } }; } // 调用方式 document.addEventListener( 'button', throttle(() => { // 重复点击按钮 }, 1000), );
也可以利用Promise进行封装