函数防抖(debounce)和函数节流(throttle)

防抖理解

做一件事情,这件事情不是立即去做,而是要等一段时间再去做,如果在这段时间内,某件事情触发了,那么就要重新计时。例如电梯门的关闭。

  • 应用
    • 窗口尺寸的改变
    • 文本框的输入,百度搜索
    • 滚动条的滚动

防抖代码

function debounce(callback,time){
    
    
	var timer;
	//为什么要返回一个函数,防止全局变量timer的污染。
	return function(){
    
    
		clearTimeout(timer);
		timer = setTimeout(()=>{
    
    
			callback.apply(null,arguments);
		},time);
	}
}

const handler = debounce((width)=>{
    
    
	console.log(width);
},1000);

window.onresize = function(){
    
    
	handler(document.documentElement.clientWidth);
}

分析:

在这里插入图片描述

  • 关于this的绑定问题。
  1. 在外面自己绑定,比如:
// 绑定this 指向window
  const func = function(width){
    
    
       console.log(width);
   }.bind(window);

   const handler = debounce(func, 1000)

   window.onresize = function () {
    
    
       handler(document.documentElement.clientWidth);
   }
  1. 将this作为参数传递进去,比如,第一个参数是传递的信息,第二个参数是传递的this。这里的代码是下面防抖应用input搜索框里面的。
const handler = debounce((val,inp) => {
    
    
            console.log('发送请求搜索' + val);
            //打印this
            cosole.log(inp)
        }, 1000);

search.oninput = function () {
    
    
	//传递this
     handler(this.value,this);
 }

防抖应用input搜索框

在input框中输入文字的时候,我们需要发送请求得到相应的内容,那么input事件会不断触发,这时就需要防抖来处理,等用户输入完后一段时间后发送请求。

 <input type="text" id="search">
 
function debounce(callback,time){
    
    
	var timer;
	return function(){
    
    
		clearTimeout(timer);
		timer = setTimeout(()=>{
    
    
			callback.apply(null,arguments);
		},time);
	}
}

const handler = debounce((val) => {
    
    
            console.log('发送请求搜索' + val);
        }, 1000);

search.oninput = function () {
    
    
     handler(this.value);
 }

函数节流理解

对于不断触发的事件,只在规定的时间内运行一次。比如,不断改变窗口的size,我在规定的时间内,只运行一次函数。与函数防抖的不同是,防抖要等到不触发这个事件后多少时间,才运行函数。

节流代码实现1

使用计时器,这个是触发事件之后,要等一段时间才运行函数。

function throttle(callback,time){
    
    
	var timer;
	return function(){
    
    
		if(timer){
    
    
			return;
		}
		timer = setTimeout(()=>{
    
    
			callback.apply(null,arguments);
			timer = null;
		},time)
	}
}

节流代码实现2

使用时间戳,触发事件后,立刻运行函数,下一次到等一段时间才运行函数。

function throttle(callback,time){
    
    
	var t;
	return function(){
    
    
		//t没有值,立即运行函数或者之前现在的时间减去运行的时间大于规定的时间
		if(!t || Date.now() - t >= time){
    
    
			
			callback.apply(null,arguments);
			//得到当前时间戳 为下一运行函数提供计算时间依据
			t = Date.now();	
		}
	}
}

图解函数防抖和函数节流

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/tscn1/article/details/115009519