防抖:app
適用於input輸入框格式驗證、聯繫詞等。待用戶中止輸入一段時間再發生請求,避免頻繁請求。this
實現細節:debounce返回一個function,關鍵點在於clearTimeout,若是用戶不停輸入,就會一直執行clearTimeout,致使fn沒法執行。只有用戶中止x時間後,纔會開始執行fn。spa
<input type="text" id="ipt">
let debounce = (fn, time) => { let timeout; return function (e) { let context = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(() => { fn.apply(context, arguments); }, (time || 200)); } }; document.getElementById('ipt').addEventListener('input', debounce((e) => { console.log(e.target.value); }, 300));
節流:節流不會像防抖那樣,等用戶行爲中止x時間後執行,而是間隔x時間執行一次。code
適用於比input、keyup更加頻繁的操做,好比mousemove、scroll、resize、touchmoveblog
實現細節:保存上次執行的時間點和定時器事件
<div id="rectangle"></div>
let throttle = (fn, time) => { let start = +new Date(), timeout; time = time || 200; return function () { let context = this, args = arguments, now = +new Date(); clearTimeout(timeout); if (now - start >= time) { console.log(1111); fn.apply(context, arguments); start = now; } else {
//讓方法在脫離事件後也能執行一次 timeout = setTimeout(() => { console.log(2222); fn.apply(context, arguments); }, time); } } }; document.getElementById('rectangle').addEventListener('mousemove', throttle((e) => { console.log(e.pageX, e.pageY); }, 1000));