在开发中,咱们经常会去监听滚动事件或者用户输入框验证事件,若是事件处理没有频率限制,就会加剧浏览器的负担,影响用户的体验感,浏览器
所以,咱们能够采起防抖(debounce)和节流(throttle)来处理,减小调用事件的频率,达到较好的用户体验。缓存
防抖(debounce):闭包
function debounce(fn, wait) { var timeout = null;// 使用闭包,缓存变量
return function() {
if(timeout !== null) { console.log('清除定时器啦') clearTimeout(timeout); //清除这个定时器 } timeout = setTimeout(fn, wait); } } // 处理函数 function handle() { console.log(Math.random()); } var container = document.getElementById('container') container.addEventListener('scroll', debounce(handle, 1000));
咱们能够发现,当连续触发scroll事件,handle函数只会在1秒时间内执行一次,在若是继续滚动执行,就会清除定时器,从新计时。至关于就是屡次执行,只执行一次。app
节流(throttle):dom
var throttle = function(func, delay) { var timer = null; // 使用闭包,缓存变量 var prev = Date.now(); // 最开始进入滚动的时间 return function() { var context = this; // this指向window var args = arguments; var now = Date.now(); var remain = delay - (now - prev); // 剩余时间 clearTimeout(timer); // 若是剩余时间小于0,就马上执行 if (remain <= 0) { func.apply(context, args); prev = Date.now(); } else { timer = setTimeout(func, remain); } } } function handle() { console.log(Math.random()); } var container = document.getElementById('container') container.addEventListener('scroll', throttle(handle, 1000));
在节流函数内部使用开始时间prev、当前时间now和剩余时间remain,当剩余时间小于等于0意味着执行处理函数,这样保证第一次就能当即执行函数而且每隔delay时间执行一次;函数
若是还没到时间,就会在remaining以后触发,保证最后一次触发事件也能执行函数,若是在remaining时间内又触发了滚动事件,那么会取消当前的计数器并计算出新的remaing时间。ui
经过时间戳和定时器的方法,咱们实现了第一次当即执行,最后一次也执行,规定时间间隔执行的效果。this
总结,看完了防抖和节流的分别介绍,咱们来看看他们的区别:spa
防抖是将屡次执行变为只执行一次,节流是将屡次执行变为每隔一段时间执行。3d
防抖(debounce)
search搜索联想,用户在不断输入值时,用防抖来节约请求资源。
window触发resize的时候,不断的调整浏览器窗口大小会不断的触发这个事件,用防抖来让其只触发一次
节流(throttle)
鼠标不断点击触发,mousedown(单位时间内只触发一次)
监听滚动事件,好比是否滑到底部自动加载更多,用throttle来判断
本文转载多出,为了让本身看得明白一点。