export function simpledebounce(func, wait = 1000, immidate = true) {
let timer = null;
return function() {
//this指向问题
let context = this;
//拿到参数
let args = [...arguments];
clearTimeout(timer);
if (immidate) {
let callNow = !timer;
timer = setTimeout(() => {
timer = null;
}, wait);
//立即执行
callNow && func.apply(context, args);
} else {
timer = setTimeout(() => {
func.apply(context, args);
}, wait);
}
};
}
/**
* 函数节流
* 触发事件立即执行,但在n秒内连续触发则不执行
*/
export function throttle(fn, wait = 1000) {
let timer;
return function() {
if (timer != null) return;
let context = this;
let args = arguments;
fn.apply(context, args);
timer = setTimeout(() => {
timer = null;
}, wait);
};
}```
```javascript
<template>
<div>
<el-button @click="debounceHandler">防抖</el-button>
<el-button @click="throttleHandler">节流</el-button>
</div>
</template>
<script>
import { simpledebounce ,throttle } from "./../utils/index"
export default {
data(){
return {
name:'仙女',
age:18
}
},
methods:{
debounceHandler:simpledebounce(function(){
console.log(this.name,"打印")
}),
throttleHandler:throttle(function(){
console.log('节流')
})
}
}
</script>
<style lang="scss" scoped>
</style>
踩坑:如下这种问题,会有作用域问题出现,如使用,请注意this的指向问题
debounceHandler(){
simpledebounce(function(){
console.log(this.name,"打印")
})
}