這篇文章是手寫實現(xiàn)xxx功能部分的第二篇,后續(xù)會陸續(xù)更新其他的。
考察點: 去抖和節(jié)流的理解以及應(yīng)用場景
去抖和節(jié)流
去抖和節(jié)流是前端非常常用的工具方法。去抖可以保證一個操作不會不停地觸發(fā)而節(jié)流可以保證在一段時間內(nèi)一個操作只能觸發(fā)一次。
節(jié)流應(yīng)用場景
節(jié)流應(yīng)用場景最多就是頁面上的事件處理了。比如鼠標滑動事件的監(jiān)聽,頁面滾動事件的監(jiān)聽等等。
這里就拿頁面滾動這個例子來說。這里我們實現(xiàn)一個常見的讀書的那種web頁面的頭部導(dǎo)航條。效果可以看這里
相應(yīng)實例代碼:
// HTML
<body>
<div id="nav"></div>
<div id="wrap"></div>
</body>
// CSS
#wrap {
background: red;
width: 300px;
height: 3300px;
margin: 0 auto;
}
#nav {
height: 10px;
background: greenyellow;
position: fixed;
top: 0;
left: 0;
width: 1px;
}
// JS
;(function() {
// 獲取屏幕高度和寬度 之所以用這個高度,是因為這個height = screenHeight + 滾動到底部是的window.scrollY
// 計算出可滾動的高度
const height = document.documentElement.scrollHeight
const width = document.documentElement.scrollWidth
const screenHeight = document.documentElement.clientHeight
const scrollHeight = height - screenHeight
const nav = document.querySelector('#nav')
window.addEventListener('scroll', function(e) {
let currentHeight = window.scrollY
nav.style.width = currentHeight/scrollHeight * width + 'px'
})
})()
但是這種實現(xiàn)方式會非常頻繁的修改DOM,這時候節(jié)流函數(shù)就體現(xiàn)處它的價值了。在這里,我直接就寫節(jié)流函數(shù)的通用方法
// 節(jié)流函數(shù)
const throttle = function(fn, timer = 500) {
let setTimeoutTimer
return function() {
if (setTimeoutTimer) return
// 這行代碼是為了方便在Vue這類框架中使用節(jié)流函數(shù)
fn && fn.call(this, ...arguments)
setTimeoutTimer = setTimeout(() => {
setTimeoutTimer = null
}, timer)
}
}
// 用法:將觸發(fā)時間修改為50ms觸發(fā)一次
window.addEventListener('scroll', throttle(function(e) {
let currentHeight = window.scrollY
nav.style.width = currentHeight/scrollHeight * width + 'px'
}, 50))
上面還有提到在Vue這類框架中用到這個節(jié)流函數(shù)的用法,我用setInterval模擬事件觸發(fā),一個簡單的demo
let vue = {
data: {
name: 'wyh'
},
say(x) {
console.log(this.data.name + x)
}
}
let fn = throttle(vue.say, 500)
setInterval(() => {
fn.call(vue, 'x')
}, 100)
去抖應(yīng)用場景
個人認為去抖在平常開發(fā)中要用的更多,最常見的場景就是動態(tài)輸入搜索(類似百度)這類功能的開發(fā)。這里就不做無去抖的效果展示了
去抖通用函數(shù)
function debounce(fn, timer = 500) {
let debounceTimer
return function() {
if (debounceTimer) {
clearTimeout(debounceTimer)
}
// 參數(shù)緩存
let args = arguments
debounceTimer = setTimeout(() => {
fn && fn.call(this, ...args)
}, timer)
}
}
實例場景
// html
<input type="text" id="input" />
// javascript
;(function() {
const i = document.querySelector('#input')
// 模擬Vue環(huán)境
let vue = {
data: {
searchStr: ''
},
/**
* 模擬搜索方法
*/
search() {
console.log(`正在以${this.data.searchStr}為檢索值進行搜索`)
}
}
let searchFn = debounce(vue.search)
i.addEventListener('input', function(e) {
// 模擬v-model
vue.data.searchStr = i.value
searchFn.call(vue)
})
})()
效果 記得打開下面的console看