js实现函数防抖和节流

  • 函数防抖(debounce),在连续的操作中,无论进行了多长时间,只有某一次的操作后在指定的时间内没有再操作,这一次才被判定有效(类似电脑10分钟后休眠)。如模糊搜索,输入框内容一直变化,会导致一直发送请求。防抖即输入内容完成后,一定时间(比如500ms)没有再输入内容,这时再触发请求。
  • ts版
<el-input v-model="keyWord" placeholder="默认拼音模糊搜索" style="width: 300px;" @keydown.native='SearchData'></el-input>

keyWord='';//检索关键词
SearchData;//属性(放函数对象)

 public async mounted() {
    this.loading = true;
    this.SearchData=this.debounce(this.SearchDataFn,800);//无论触发多少次,都只会在800毫秒后执行查询代码
    await this.SearchData();//查询数据
    this.loading = false;
  }

//防抖
debounce(fn, wait) {
    let timer = null;
    let that = this;
    return function () {
      let arg = arguments;
      if (timer !== null) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fn.apply(null, arg)
      }, wait);
    }
}

  async SearchDataFn(){
	  //ts代码编写的调用查询webapi
  }
  • js版
function Demo(e){
    console.log(this);
    console.log(e);
}

function debounce(fn,wait){
    let timer=null;
    return function(){
        if(timer!==null){
            clearTimeout(timer);
        }
        timer=setTimeout(()=>{
            fn.apply(this,arguments)
        },wait);
    }
}
let Demo1=debounce(Demo,300);

  • 节流,规定时间内,只触发一次。如用快捷键提交表单,如果1s内多次触发快捷键,就会重复提交。每次发送请求,会给服务器造成巨大的压力,但是我们进行节流后,就会大大减少请求的次数。
<script>
	var timer1;
	function throttle(fn, delay) {
		if (timer1) {
			return;
		}
		timer1 = setTimeout(function () {
								fn(); 
								timer1 = null; 
							},delay);
	}

	function testThrettle() {
		console.log('js节流');
	}

	document.onmousemove = () => {
		throttle(testThrettle, 10);
	}
</script>

//【ts版】
outTimer=null;
//js节流
throttle(fn, delay) {
    let that = this;
    if (this.outTimer) {
      return;
    }
    this.outTimer = setTimeout(function () {
      fn();
      that.outTimer = null;
    }, delay);
  }

posted on 2021-11-19 09:51  anjun_xf  阅读(816)  评论(0编辑  收藏  举报

导航

TOP