概念: 在事件被触发n秒后再执行回调,若是在这n秒内又被触发,则从新计时。app
生活中的实例: 若是有人进电梯(触发事件),那电梯将在10秒钟后出发(执行事件监听器),这时若是又有人进电梯了(在10秒内再次触发该事件),咱们又得等10秒再出发(从新计时)。dom
对于函数防抖,有如下几种应用场景:函数
function debounce(fn, wait) { var timer = null; return function () { if (timer !== null) { clearTimeout(timer);//若是屡次触发将上次记录延迟清除掉 } timer = setTimeout(function () { fn.apply(this, arguments) }, wait) } } // 处理函数 function handle() { console.log(Math.random()); } // 事件 window.addEventListener("scroll", debounce(handle, 1000)); //滚动结束一秒后打印 setInterval(debounce(handle,2000),1000) // 不会触发一次(我把函数防抖看出技能读条,若是读条没完成就用技能,便会失败并且从新读条)
概念: 规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,若是在同一个单位时间内某事件被触发屡次,只有一次能生效。动画
生活中的实例: 咱们知道目前的一种说法是当 1 秒内连续播放 24 张以上的图片时,在人眼的视觉中就会造成一个连贯的动画,因此在电影的播放(之前是,如今不知道)中基本是以每秒 24 张的速度播放的,为何不 100 张或更可能是由于 24 张就能够知足人类视觉需求的时候,100 张就会显得很浪费资源。this
对于函数节流,有以下几个场景:code
//时间戳方式 function throttle(fn, gapTime) { let _lastTime = null; return function () { let _nowTime = + new Date() if (_nowTime - _lastTime > gapTime || !_lastTime) { fn(); _lastTime = _nowTime } } } // 处理函数 let handle = ()=>{ console.log(Math.random()) } // 事件函数 window.addEventListener('scroll',throttle(handle,1000)) //定时器方式 let throttle = function(func, delay) { let timer = null; return ()=> { if (!timer) { timer = setTimeout(()=> { func.apply(this, arguments); timer = null; }, delay); } }; }; function handle() { console.log(Math.random()); } window.addEventListener("scroll", throttle(handle, 1000));