完全参考,此处为整理笔记
[有趣面试题] 网页效能问题改善之 Debounce & Throttle
Debounce & Throttle — 那些前端开发应该要知道的小事(一)
适用情境
只要是使用者会在短时间内频繁触发多次事件处理器,例如:
autocomplete、滑鼠移动、改变视窗大小都可以适用此篇。因为你的浏览器会不断重新计算造成页面很缓慢
如Vue的computed因内部变数变动,致重複触发,此时可使用debounce设定触发时间,节省效能
<input type="text" id="debounce-input" placeholder="type something" /><input type="text" id="throttle-input" placeholder="type something" />
debounce
所谓 Debounce,是让使用者在触发相同事件(如卷轴)的情境下,停止触发绑定事件的效果,直到使用者停止触发相同事件。
因为使用者输入一次你就要 filter 一次,假如使用者频繁输入就可能会影响到效能
设一个 timeout,例如输入以后过两秒才去抓一次使用者输入值
好处就是可以防止 js 频繁去筛选资料,等待两秒后再一次筛选就好
// func: 要执行的 function // delay: 延迟几秒才执行 function debounce(func, delay) { // timeout 初始值 let timeout = null; return function () { let context = this; // 指向 myDebounce 这个 input let args = arguments; // KeyboardEvent clearTimeout(timeout); timeout = setTimeout(function () { func.apply(context, args); }, delay); }; } // 1 2秒后执行 // 2 前一个清掉,2秒后执行 1 2 // 3 前一个清掉,2秒后执行 1 2 3 let myDebounce = document.getElementById("debounce-input"); // myDebounce.addEventListener('keyup', function(e){ // console.log(e.target.value) // }) myDebounce.addEventListener( "keyup", debounce(function (e) { console.log(e.target.value); }, 2000) );
throttle
为使用者触发相同事件时提供间隔,控制特定时间内事件触发的次数。
它防止一下输入太频繁的值,所以会限制一个时间,在这时间内触发的值会被存到下一次再存
function throttle(func, delay) { let inThrottle; let timeout = null; return function () { let context = this; let args = arguments; if (!inThrottle) { // 输入之后两秒内都不回进入这边 func.apply(context, args); inThrottle = true; clearTimeout(timeout); timeout = setTimeout(function () { inThrottle = false; }, delay); } }; } document.getElementById("throttle-input").addEventListener( "keyup", throttle(function (e) { console.log(e.target.value); }, 2000) );