函数防抖Debounce和函数节流Throttle
函數(shù)節(jié)流 & 函數(shù)防抖
函數(shù)節(jié)流和函數(shù)防抖
函數(shù)節(jié)流和函數(shù)防抖二者很容易被混淆起來。下面貼英文原文,建議認真閱讀:
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".
函數(shù)節(jié)流:確保函數(shù)特定的時間內(nèi)至多執(zhí)行一次。
函數(shù)防抖:函數(shù)在特定的時間內(nèi)不被再調(diào)用后執(zhí)行。
上面的概念可能還是不夠清晰,下面均以“輸入框輸入文字觸發(fā)ajax獲取數(shù)據(jù)”為例,分別以防抖和節(jié)流的思想來優(yōu)化,二者的區(qū)別:
輸入框輸入文字如下:1111111111111111111111(停頓3s繼續(xù)輸入)11111111111111111
函數(shù)防抖:當用戶持續(xù)輸入1的過程中,并不會發(fā)送ajax,當用戶停止輸入2s后,發(fā)送ajax請求,之后到第3s后,用戶繼續(xù)輸入1的過程中,依舊不會發(fā)送ajax,當用戶停止輸入2s后,又觸發(fā)ajax請求。
函數(shù)節(jié)流:當用戶持續(xù)輸入1的過程中(假設輸入1的過程超過2s了),從你開始輸入1開始計時,到第2s,發(fā)送ajax請求。函數(shù)節(jié)流與你是否停止輸入無關(guān),是一種周期性執(zhí)行的策略。
一句話概括:函數(shù)節(jié)流是從用戶開始輸入就開始計時,而函數(shù)節(jié)流是從用戶停止輸入開始計時。
場景分析
函數(shù)節(jié)流(throttle)
函數(shù)防抖(debounce)
注:throttle和debounce均是通過減少實際邏輯處理過程的執(zhí)行來提高事件處理函數(shù)運行性能的手段,并沒有實質(zhì)上減少事件的觸發(fā)次數(shù)。
使用函數(shù)節(jié)流是進行前端性能優(yōu)化的方法之一,例如,懶加載的實現(xiàn)。
實現(xiàn)函數(shù)防抖和函數(shù)節(jié)流
函數(shù)防抖
function debounce(func,wait){var timeout;return function(){var context=this;//用來保存this的正確指向var args=arguments;//用來保存觸發(fā)的事件類型,例如keyboard eventclearTimeout(timeout);//每次都重新開始計時timeout=setTimeout(function(){func.apply(context,args);},wait);} } a.onkeyup=debounce(getValue,3000); function getValue(){console.log(this.value);//使用debounce調(diào)用它時,this就變?yōu)閣indow }函數(shù)節(jié)流
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();//下次觸發(fā) func 剩余的時間var remaining = wait - (now - previous);context = this;args = arguments;// 如果沒有剩余的時間了或者你改了系統(tǒng)時間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; }總結(jié)
以上是生活随笔為你收集整理的函数防抖Debounce和函数节流Throttle的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AWS Elastic Block St
- 下一篇: 4MLinux 24.0 发布