防抖和节流的使用

本文介绍了JavaScript中两种优化性能的技术:防抖(debounce)和节流(throttle)。通过示例代码展示了如何实现这两个功能,特别强调了在事件处理函数中如何处理`this`指向问题。在实际开发中,防抖常用于限制函数的执行频率,如输入框搜索事件,而节流则用于确保在一定时间内只执行一次,如滚动事件监听。
摘要由CSDN通过智能技术生成
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,"打印")
    })
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值