防抖、节流实战应用

概念:

防抖:周期内有新事件触发,清除旧定时器,重置新定时器

/*
*func:回调函数
*wait:执行时间
*/

// 防抖
function debounce(func, wait) {
    
    
    var timerId = null;
    return function (...args) {
    
    
      if (timerId) {
    
    
         clearTimeout(timerId);
       }
        timerId = setTimeout(() => {
    
    
            func.apply(this,args);
        }, wait);
     }
}
 // 实例化防抖函数
var antiShake = debounce(fn, 1000)
// 调用函数传入value
 antiShake(value)

概念:

节流:触发高频事件后n秒内函数也只会执行一次,但如果一直被触发,则每n秒执行一次,相当于稀释函数的执行频率

/*
*func:回调函数
*time:执行时间
*/
// 节流
function throttleTimer(func, time){
    
    
  let timerId = null
  return function () {
    
    
    var args = arguments
    if (!timer) {
    
    
      timerId = setTimeout(function () {
    
    
        func.apply(this,args)
        timerId = null
      }, time)
    }
  }
}
 // 实例化节流函数
var throttle= throttleTimer(fn, 1000)
// 调用函数传入value
 throttle(value)

猜你喜欢

转载自blog.csdn.net/lyf976229437/article/details/111945769