1.节流(throttle )
示例代码
let timer = null
function throttle (fn, delay = 300) {
if(timer == null){
timer = setTimeout(() => {
fn()
clearTimeout(timer)
timer = null
}, delay);
}
}
使用
throttle(()=> count += 1, 1000)
2.节流(throttle )
示例代码
let timer = null
function throttle (fn, delay = 300) {
if(timer == null){
timer = setTimeout(() => {
fn()
clearTimeout(timer)
timer = null
}, delay);
}
}
使用
throttle(()=> count += 1, 1000)
防抖(debounce)js封装
function debounce (fn, delay = 300){
let timer = null
return function (...args) {
if(timer != null){
clearTimeout(timer)
timer = null
}
timer = setTimeout(()=>{
fn.call(this, ...args)
}, delay);
}
}
使用
const addCount = debounce(()=> count.value += 1, 1000)
常见封装-2
let timer = null
function debounce (fn, delay = 1000){
if(timer != null){
clearTimeout(timer)
timer = null
}
timer = setTimeout(fn, delay)
}
使用
const addCount = () => debounce(()=> count.value += 1, 1000)
vue 3
中的 customRef
来实现我们的新方式
// 从 vue 中引入 customRef 和 ref
import { customRef, ref } from "vue"
// data 为创建时的数据
// delay 为防抖时间
function debounceRef (data, delay = 300){
// 创建定时器
let timer = null;
// 对 delay 进行判断,如果传递的是 null 则不需要使用 防抖方案,直接返回使用 ref 创建的。
return delay == null
?
// 返回 ref 创建的
ref(data)
:
// customRef 中会返回两个函数参数。一个是:track 在获取数据时收集依赖的;一个是:trigger 在修改数据时进行通知派发更新的。
customRef((track, trigger) => {
return {
get () {
// 收集依赖
track()
// 返回当前数据的值
return data
},
set (value) {
// 清除定时器
if(timer != null){
clearTimeout(timer)
timer = null
}
// 创建定时器
timer = setTimeout(() => {
// 修改数据
data = value;
// 派发更新
trigger()
}, delay)
}
}
})
}
使用
// 创建
const count = debounceRef(0, 300)
// 函数中使用
const addCount = () => {
count.value += 1
}
// v-model 中使用
<input type="text" v-model="count">
节流(throttle)
常见封装-1
let timer = null
function throttle (fn, delay = 300) {
if(timer == null){
timer = setTimeout(() => {
fn()
clearTimeout(timer)
timer = null
}, delay);
}
}
使用
const addCount = () => throttle(()=> count.value += 1, 1000)
常见封装-2
function throttle (fn, delay = 300) {
let timer = null
return function (...args) {
if(timer == null){
timer = setTimeout(() => {
fn.call(this, ...args)
clearTimeout(timer)
timer = null
}, delay);
}
}
}
使用
const addCount = throttle(()=> count.value += 1, 1000)
新封装
// data 为创建时的数据
// delay 为节流时间
function throttleRef (data, delay = 300){
// 创建定时器
let timer = null;
// 对 delay 进行判断,如果传递的是 null 则不需要使用 节流方案,直接返回使用 ref 创建的。
return delay == null
?
// 返回 ref 创建的
ref(data)
:
// customRef 中会返回两个函数参数。一个是:track 在获取数据时收集依赖的;一个是:trigger 在修改数据时进行通知派发更新的。
customRef((track, trigger) => {
return {
get () {
// 收集依赖
track()
// 返回当前数据的值
return data
},
set (value) {
// 判断
if(timer == null){
// 创建定时器
timer = setTimeout(() => {
// 修改数据
data = value;
// 派发更新
trigger()
// 清除定时器
clearTimeout(timer)
timer = null
}, delay)
}
}
}
})
}
使用
// 创建
const count = debounceRef(0, 300)
// 函数中使用
const addCount = () => {
count.value += 1
}
// v-model 中使用
<input type="text" v-model="count">