什么是防抖

函数防抖:是指在事件被触发 n 秒后再执行回调,如果在这 n 秒内事件又被触发,则重新计时。这可以使用在一些点击请求的事件上,避免因为用户的多次点击向后端发送多次请求。

实现防抖

  1. const debounce = (fn, wait)=>{
  2. const timer = null;
  3. return function (){
  4. const context = this;
  5. const args = arguments;
  6. if(timer){
  7. clearTimeout(timer);
  8. timer = null;
  9. }
  10. timer = setTimeout(()=>{
  11. fn.applycontext, args
  12. },wait)
  13. }
  14. }

什么是节流

函数节流:是指规定一个单位时间,在这个单位时间内,只能有一次触发事件的回调函数执行,如果在同一个单位时间内某事件被触发多次,只有一次能生效。节流可以使用在 scroll 函数的事件监听上,通过事件节流来降低事件调用的频率。

实现节流

  1. function throttle(fn, delay) {
  2. let preTime = Date.now();
  3. return function() {
  4. const context = this;
  5. let args = arguments;
  6. let nowTime = Date.now();
  7. // 如果时间间隔超过指定时间,则执行函数
  8. if (nowTime - preTime > delay) {
  9. preTime = nowTime
  10. return fn.apply(context, args)
  11. }
  12. };
  13. }