滑動到底部繼續加載,是移動端很常見的一種場景。
一般來講,咱們會在對可滑動區域(通常是window)的scroll事件作監聽,判斷距離底部還有多遠,若是距離底部較近,則發起HTTP請求,請求下一頁的數據。
很容易寫出這樣的代碼:javascript
let page = 0; document.querySelector('.main').addEventListener('scroll', () => { scrollMore(this); }) // 滑動獲取更多內容 function scrollMore(el) { if (getScrollTop(el) + getClientHeight() >= getScrollHeight(el) - 100) { fetch('http://api.jd.com/somethings/' + page++) .then(function(response) { console.log(response.json()); // do something 把數據填充到頁面上 }) } } function getScrollTop(el) { //取窗口滾動條高度 return el.scrollTop; } function getClientHeight() { //取窗口可視範圍的高度 let clientHeight = 0; if (document.body.clientHeight && document.documentElement.clientHeight) { clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight; } else { clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight; } return clientHeight; } function getScrollHeight(el) { //取文檔內容實際高度 return Math.max(document.body.scrollHeight, el.scrollHeight); }
可是這樣很容易就發現一個問題,觸發的scroll事件太頻繁了,在一些低端機上,可能會卡頓。
其實咱們的判斷沒有必要這麼頻繁,用戶的滑動操做是一段時間內不停觸發的。
咱們但願在一小段時間內,只觸發一次執行。java
這就是函數節流要作的事情,《JavaScript高級程序設計》中給了一個方法:json
function throttle (method, context) { clearTimeout(method.tId); method.tId = setTimeout(function () { method.call(context); }, 100) }
這個代碼的原理就是在屢次執行的時候,清除上一次的timeout,若是時間間隔沒有超過100ms,則又新建一個新的timeout,舊的則被丟棄。
考慮一下,若是在一段時間內,每隔99ms觸發一次,那麼不停地清除上一次的timeout,函數將永遠不會執行。
咱們更但願,每隔100ms,函數就執行一次,而不是像如今同樣。
從新思考這個問題。
關鍵點有兩個:api
先來把函數封裝一下,將節流函數return出來:app
function throttle1 (method, delay) { let timer = null; return function () { let context = this ; if (timer) clearTimeout(timer); timer = setTimeout(() => { method.call(context); }, delay) } }
加上間隔斷定:函數
function throttle2 (method, delay) { let timer = null; let start; return function () { let context = this , current = Date.now() ; if (timer) clearTimeout(timer); if (!start) { start = current; } if (current - start >= delay) { method.call(context); start = current; } else { timer = setTimeout(() => { method.call(context); }, delay) } } }
這樣,基本上完成了一個throttle函數。fetch
防抖的場景也比較常見。
好比搜索時,監聽用戶輸入,提供聯想詞;或者用戶連續點擊提交按鈕的場景。
說實話,我感受《高級》那本書裏的節流例子,就是一個防抖的版本。
幾乎能夠拿來就用。
咱們仍是作一個比較完善的版本。this
function debounce (method, delay) { let timeout = null; return function () { clearTimeout(timeout); timeout = setTimeout(() => { method.apply(this, arguments); }, delay); }; }