我正在参与掘金创作者训练营第6期, 点击了解活动详情
认识防抖和节流函数
-
防抖和节流的概念其实最早并不是出现在软件工程中,防抖是出现在电子元件中,节流出现在流体流动中
- 而JavaScript是事件驱动的,大量的操作会触发事件,加入到事件队列中处理。
- 而对于某些频繁的事件处理会造成性能的损耗,我们就可以通过防抖和节流来限制事件频繁的发生;
-
防抖和节流函数目前已经是前端实际开发中两个非常重要的函数,也是面试经常被问到的面试题
-
但是很多前端开发者面对这两个功能,有点摸不着头脑:
- 一些同学根本无法区分防抖和节流有什么区别(面试经常会被问到);
- 一些同学可以区分,但是不知道如何应用;
- 一些同学会通过一些第三方库来使用,但是不知道内部原理,更不会编写;
接下来我们会一起来学习防抖和节流函数:
-
我们不仅仅要区分清楚防抖和节流两者的区别,也要明白在实际工作中哪些场景会用到;
-
那么让我们一点点来编写一个自己的防抖和节流的函数,不仅理解原理,也学会自己来编写;
认识防抖debounce函数
- 我们用一副图来理解一下它的过程:
- 当事件触发时,相应的函数并不会立即触发,而是会等待一定的时间;
- 当事件密集触发时,函数的触发会被频繁的推迟;
- 只有等待了一段时间也没有事件触发,才会真正的执行响应函数;
防抖的应用场景很多:
- 输入框中频繁的输入内容,搜索或者提交信息;
- 频繁的点击按钮,触发某个事件;
- 监听浏览器滚动事件,完成某些特定操作;
- 用户缩放浏览器的resize事件;
防抖函数的案例
-
我们都遇到过这样的场景,在某个搜索框中输入自己想要搜索的内容
-
比如想要搜索一个iphone13:
- 当我输入i时,为了更好的用户体验,通常会出现对应的联想内容,这些联想内容通常是保存在服务器的,所以需要一次网络请求;
- 当继续输入ip时,再次发送网络请求;
- 那么iphone13一共需要发送8次网络请求;
- 这大大损耗我们整个系统的性能,无论是前端的事件处理,还是对于服务器的压力;
-
本地测试案例:
<body>
<input type="text">
<script src="https://cdn.jsdelivr.net/npm/underscore@1.13.4/underscore-umd-min.js"></script>
<script>
// 1.获取输入框
const inp = document.querySelector('input')
// 2. 监听输入框内容,模拟发送ajax请求
// 2.1定义一个监听函数
let num = 0
inp.oninput = function () {
console.log(`发送了${++num}次请求`)
}
</script>
</body>
- 但是我们需要这么多次的网络请求吗?
- 不需要,正确的做法应该是在合适的情况下再发送网络请求;
- 比如如果用户快速的输入一个iphone13,那么只是发送一次网络请求;
- 比如如果用户是输入一个i想了一会儿,这个时候i确实应该发送一次网络请求;
- 也就是我们应该监听用户在某个时间,比如500ms内,没有再次触发时间时,再发送网络请求;
- 这就是防抖的操作:只有在某个时间内,没有再次触发某个函数时,才真正的调用这个函数;
Underscore库的介绍
- 事实上我们可以通过一些第三方库来实现防抖操作:
- lodash
- underscore
- 这里使用underscore
- 我们可以理解成lodash是underscore的升级版,它更重量级,功能也更多;
- 但是目前我看到underscore还在维护,lodash已经很久没有更新了;
- Underscore的官网: underscorejs.org/
- Underscore的安装有很多种方式:
- 下载Underscore,本地引入;
- 通过CDN直接引入;
- 通过包管理工具(npm)管理安装;
- 我们直接通过CDN:
<body>
<input type="text">
<script src="https://cdn.jsdelivr.net/npm/underscore@1.13.4/underscore-umd-min.js"></script>
<script>
// 1.获取输入框
const inp = document.querySelector('input')
let num = 0
const changeFn = function () {
console.log(`发送了${++num}次请求`)
}
// 实现防抖
inp.oninput = _.debounce(changeFn, 1000)
// 实现节流
inp.oninput = _.throttle(changeFn, 1000)
</script>
</body>
- 通过第三方库就已经实现了防抖跟节流了
自定义防抖和节流函数
- 虽然我们可以通过第三方来实现防抖跟节流,但是我们还没明白其中的原理,接下来我们自己来实现一下防抖
- 我们按照如下思路来实现:
- 整体代码如下:
<body>
<input type="text">
<script>
const inp = document.querySelector('input')
let counter = 0
const change = function(event) {
console.log(`发送了第${++counter}次网络请求`, this, event)
}
inp.oninput = debounce(change, 1000)
</script>
</body>
- 防抖基本功能实现:可以实现防抖效果
const debounce = function (fn, delay) {
// 1.定义一个定时器, 保存上一次的定时器
let timer = null
// 2.真正执行的函数
const _debounce = function () {
// 取消上一次的定时器
if(timer) clearTimeout(timer)
// 延迟执行
timer = setTimeout(() => {
// 外部传入的真正需要执行的函数
// 这里需要绑定this和参数
fn()
}, delay)
}
return _debounce
}
- 优化一:优化参数和this指向(到这一步基本满足大部分的需求了)
const debounce = function (fn, delay) {
let timer = null
const _debounce = function (...args) {
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
return _debounce
}
- 优化二:优化取消操作(增加取消功能)
const debounce = function (fn, delay, immediate = false) {
let timer = null
let isInvoke = false
const _debounce = function (...args) {
if(timer) clearTimeout(timer)
if(immediate && !isInvoke) {
fn.apply(this, args)
isInvoke = true
} else {
// 延迟执行
timer = setTimeout(() => {
fn.apply(this, args)
isInvoke = false
}, delay)
}
}
// 给_debounce上加一个取消的方法
_debounce.cancelFn = function () {
if(timer) clearTimeout(timer)
timer = null
isInvoke = false
}
return _debounce
}
debounceChange = debounce(change, 3000)
inp.oninput = debounceChange
const btn = document.querySelector('button')
btn.onclick = function () {
// 取消
debounceChange.cancelFn()
}
- 优化三:优化立即执行效果(第一次立即执行)
const debounce = function (fn, delay, immediate = false) {
let timer = null
let isInvoke = false
const _debounce = function (...args) {
if(timer) clearTimeout(timer)
if(immediate && !isInvoke) {
fn.apply(this, args)
isInvoke = true
} else {
timer = setTimeout(() => {
fn.apply(this, args)
isInvoke = false
}, delay)
}
}
return _debounce
}
- 优化四:优化返回值
const debounce = function (fn, delay, immediate = false, resultCallback) {
let timer = null
let isInvoke = false
const _debounce = function (...args) {
if(timer) clearTimeout(timer)
if(immediate && !isInvoke) {
const result = fn.apply(this, args)
resultCallback(result)
isInvoke = true
} else {
timer = setTimeout(() => {
const result = fn.apply(this, args)
resultCallback(result)
isInvoke = false
}, delay)
}
}
_debounce.cancelFn = function () {
if(timer) clearTimeout(timer)
timer = null
isInvoke = false
}
return _debounce
}
const change = function(event) {
console.log(`发送了第${++counter}次网络请求`, this, event)
return '我是返回值'
}
debounceChange = debounce(change, 1000, false, function (res){
console.log('返回参数', res)
})
inp.oninput = debounceChange
如此就是一个非常完整的防抖了,回调其实还可以使用new Promise来接收返回值
认识节流throttle函数
- 我们用一副图来理解一下节流的过程
- 当事件触发时,会执行这个事件的响应函数;
- 如果这个事件会被频繁触发,那么节流函数会按照一定的频率来执行函数;
- 不管在这个中间有多少次触发这个事件,执行函数的频繁总是固定的;
节流的应用场景:
- 监听页面的滚动事件;
- 鼠标移动事件;
- 用户频繁点击按钮操作;
- 游戏中的一些设计;
防抖函数的案例
- 我们遇到过这样的需求,监听鼠标在浏览器中移动的时候的坐标, 这时候鼠标移动是非常频繁的, 那我们可以这么做,不管用户移动的多快, 我们只会以一个固定频率再执行,比如说每隔2秒或者几秒来执行
自定义节流函数
- 虽然我们可以通过第三方来实现防抖跟节流,但是我们还没明白其中的原理,接下来我们自己来实现一下防抖
- 我们按照如下思路来实现:
- 整体代码如下:
<body>
<input type="text">
<script>
const inp = document.querySelector('input')
let num = 0
inp.oninput = function () {
console.log(`发送了${++num}次请求`)
}
</script>
</body>
- 防抖基本功能实现:可以实现防抖效果
function throttle(fn, interval, options) {
// 1.记录上一次的开始时间
let lastTime = 0
// 2.事件触发时, 真正执行的函数
const _throttle = function() {
// 2.1.获取当前事件触发时的时间
const nowTime = new Date().getTime()
// 2.2.使用当前触发的时间和之前的时间间隔以及上一次开始的时间, 计算出还剩余多长事件需要去触发函数
const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
// 2.3.真正触发函数
fn()
// 2.4.保留上次触发的时间
lastTime = nowTime
}
}
return _throttle
}
- 节流最后一次也可以执行
function throttle(fn, interval, options = { leading: true, trailing: false }) {
const { leading, trailing } = options
let lastTime = 0
const _throttle = function() {
const nowTime = new Date().getTime()
if (!lastTime && !leading) lastTime = nowTime
const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
fn()
lastTime = nowTime
}
}
return _throttle
}
- 优化添加取消功能
function throttle(fn, interval, options = { leading: true, trailing: false }) {
const { leading, trailing } = options
let lastTime = 0
let timer = null
const _throttle = function(...args) {
const nowTime = new Date().getTime()
if (!lastTime && !leading) lastTime = nowTime
const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
if (timer) {
clearTimeout(timer)
timer = null
}
fn.apply(this, args)
lastTime = nowTime
return
}
if (trailing && !timer) {
timer = setTimeout(() => {
timer = null
lastTime = !leading ? 0: new Date().getTime()
fn.apply(this, args)
}, remainTime)
}
}
_throttle.cancel = function() {
if(timer) clearTimeout(timer)
timer = null
lastTime = 0
}
return _throttle
}
- 优化返回值问题
function throttle(fn, interval, options = { leading: true, trailing: false }) {
const { leading, trailing, resultCallback } = options
let lastTime = 0
let timer = null
const _throttle = function(...args) {
return new Promise((resolve, reject) => {
const nowTime = new Date().getTime()
if (!lastTime && !leading) lastTime = nowTime
const remainTime = interval - (nowTime - lastTime)
if (remainTime <= 0) {
if (timer) {
clearTimeout(timer)
timer = null
}
const result = fn.apply(this, args)
if (resultCallback) resultCallback(result)
resolve(result)
lastTime = nowTime
return
}
if (trailing && !timer) {
timer = setTimeout(() => {
timer = null
lastTime = !leading ? 0: new Date().getTime()
const result = fn.apply(this, args)
if (resultCallback) resultCallback(result)
resolve(result)
}, remainTime)
}
})
}
_throttle.cancel = function() {
if(timer) clearTimeout(timer)
timer = null
lastTime = 0
}
return _throttle
}
- 以上就是完整的防抖跟节流的实现了
- 如有需要直接可复制最终的版本到自己的utils里面,引入可直接使用
- 如有不足,也欢迎大家指出