本文主要介紹了JS函數節流防手震,函數節流和函數防手震為了解決類似需求應運而生的,有興趣的可以了解一下,希望能幫助大家。
在前端開發有一部分的使用者行為會頻繁的觸發事件執行,而對於DOM操作、資源載入等耗費效能的處理,很可能會導致介面卡頓,甚至是瀏覽器的崩潰。函數節流(throttle)和函數防手震(debounce)就是為了解決類似需求應運而生的。
函數節流(throttle)
函數節流就是預定函數只有在大於等於執行週期時才執行,週期內呼叫不執行。好像水滴攢到一定重量才會落下一樣。
場景:
視窗調整(resize)
#頁面捲動(scroll)
搶購瘋狂點擊(mousedown)
實作:
function throttle(method, delay){ var last = 0; return function (){ var now = +new Date(); if(now - last > delay){ method.apply(this,arguments); last = now; } } } document.getElementById('throttle').onclick = throttle(function(){console.log('click')},2000);
underscore實作:
##
_.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; //计算剩余时间 var remaining = wait - (now - previous); context = this; args = arguments; //剩余时间小于等于0或者剩余时间大于等待时间(本地时间变动出现) if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; };
場景:
拖曳(mousemove)
_.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; };
以上是JS函數節流防手震實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!