封装防抖函数 / 封装节流函数,并执行

257 阅读1分钟

防抖:debounce,并执行。

// 防抖
function debounce(fn, delay) {
	let timer = null;
	return function (){
		let context = this;
		let args = arguments;
		clearTimeout(timer)
		timer = setTimeout(() => {
			fn.apply(context, args);
			console.log('8=====');
		}, delay);
	}
}

const fnc = () =>{	console.log('888');	}

const x = debounce(fnc, 500)
x(1);
x(2);
x(3);
console.log(x, 'x======');
  // 防抖 
  <input id="input1" type="text" />    // 一个input框
  const input1 = document.getElementById('input1');
  function debounce1(fn, dealy){
    let timer = null;
    if(timer){
      clearTimeout(tiemr);
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments)
      timer = null;
    }, delay)
  }
  input1.addEventListener('keyup', debounce(aaa, 500))
//  在react里面  防抖
  function debounce2(delay){
    let timer = null;
    return function(){
      if(timer){
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        console.log('防抖---打印')
        timer = null;
      }, delay)
    }
  }
  <div>
    <input onClick={debounce2(500)}> </input> // 结果就是:点击一次,500毫米之后执行;多次点击的话,重新计时。
  </div>

节流:throttle,并执行。

  // 节流
  function throttle(delay){
    let timer = null;
    return function(){
      if(timer){
        retrn
      }
      timer = setTimeout(() => {
        console.log('节流---打印')
        timer = null;
      }, delay)
    }
  }

  <div>
    <input onClick={throttle(500)}> </input> // 结果就是:点击多次,在500毫秒内,只有一次生效;等过了500毫秒,才可进行第二次执行。
  </div>