函数防抖Debounce和函数节流Throttle
函數節流 & 函數防抖
函數節流和函數防抖
函數節流和函數防抖二者很容易被混淆起來。下面貼英文原文,建議認真閱讀:
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called".
Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds".
函數節流:確保函數特定的時間內至多執行一次。
函數防抖:函數在特定的時間內不被再調用后執行。
上面的概念可能還是不夠清晰,下面均以“輸入框輸入文字觸發ajax獲取數據”為例,分別以防抖和節流的思想來優化,二者的區別:
輸入框輸入文字如下:1111111111111111111111(停頓3s繼續輸入)11111111111111111
函數防抖:當用戶持續輸入1的過程中,并不會發送ajax,當用戶停止輸入2s后,發送ajax請求,之后到第3s后,用戶繼續輸入1的過程中,依舊不會發送ajax,當用戶停止輸入2s后,又觸發ajax請求。
函數節流:當用戶持續輸入1的過程中(假設輸入1的過程超過2s了),從你開始輸入1開始計時,到第2s,發送ajax請求。函數節流與你是否停止輸入無關,是一種周期性執行的策略。
一句話概括:函數節流是從用戶開始輸入就開始計時,而函數節流是從用戶停止輸入開始計時。
場景分析
函數節流(throttle)
函數防抖(debounce)
注:throttle和debounce均是通過減少實際邏輯處理過程的執行來提高事件處理函數運行性能的手段,并沒有實質上減少事件的觸發次數。
使用函數節流是進行前端性能優化的方法之一,例如,懶加載的實現。
實現函數防抖和函數節流
函數防抖
function debounce(func,wait){var timeout;return function(){var context=this;//用來保存this的正確指向var args=arguments;//用來保存觸發的事件類型,例如keyboard eventclearTimeout(timeout);//每次都重新開始計時timeout=setTimeout(function(){func.apply(context,args);},wait);} } a.onkeyup=debounce(getValue,3000); function getValue(){console.log(this.value);//使用debounce調用它時,this就變為window }函數節流
function throttle(func, wait) {var timeout, context, args, result;var previous = 0;var later = function() {previous = +new Date();timeout = null;func.apply(context, args)};var throttled = function() {var now = +new Date();//下次觸發 func 剩余的時間var remaining = wait - (now - previous);context = this;args = arguments;// 如果沒有剩余的時間了或者你改了系統時間if (remaining <= 0 || remaining > wait) {if (timeout) {clearTimeout(timeout);timeout = null;}previous = now;func.apply(context, args);} else if (!timeout) {timeout = setTimeout(later, remaining);}};return throttled; }總結
以上是生活随笔為你收集整理的函数防抖Debounce和函数节流Throttle的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AWS Elastic Block St
- 下一篇: 4MLinux 24.0 发布