<template>
<div>
<el-input @input="debounceIpt" v-model="debounceVal" placeholder="防抖" clearable></el-input>
<el-input @input="throttleIpt" v-model="throttleVal" placeholder="节流" clearable></el-input>
</div>
</template>
<script>
export default {
data() {
return {
debounceVal: '',
throttleVal: ''
};
},
mounted() {
this.debounceLogFn = this.debounce(this.debounceLog)
this.throttleLogFn = this.throttle(this.throttleLog)
},
methods: {
// 防抖输入
debounceIpt(val) {
this.debounceLogFn(val)
},
// 防抖目标操作
debounceLog(val) {
console.log(val, 'val+++')
},
// 防抖封装
debounce(fn, delay = 1000, isFirst = true) {
let timer = null
let isFirstInner = true
return function _debounce() {
// 第一次是否立即执行
if(isFirstInner && isFirst) {
fn.apply(this, arguments)
isFirstInner = false
}
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, arguments)
}, delay)
}
},
// 节流输入
throttleIpt(val) {
this.throttleLogFn(val)
},
// 节流目标操作
throttleLog(val) {
console.log(val, 'val+++')
},
// 节流封装
throttle(fn, delay = 1000, isFirst = false, isLastest = true) {
let lastTime = 0
let isFirstInner = false
let timer = null
return function _throttle() {
let nowTime = +new Date()
// 第一次是否立即执行
if(!isFirstInner && !isFirst) {
lastTime = nowTime
isFirstInner = true
}
let remainTime = nowTime - lastTime
if(remainTime >= delay) {
fn.apply(this, arguments)
lastTime = nowTime
} else {
if(timer) clearTimeout(timer)
timer = setTimeout(() => {
if(isLastest) fn.apply(this, arguments) // 是否执行最后一次输入
isFirstInner = false // 第二次输入 首次是否立即执行
}, delay)
}
}
}
}
};
</script>
<style></style>
节流、防抖函数封装并测试
于 2024-03-01 15:34:35 首次发布