首页 > 其他 > 详细

点击事件的防抖和节流

时间:2020-04-30 16:00:36      阅读:560      评论:0      收藏:0      [点我收藏+]

1.新建js文件

// 防抖:多次触发事件后,事件处理函数只执行一次,并且是在触发操作结束时执行。
export function debounce(fn, delay) {


  var delay = delay || 200;
  var timer;
  return function () {
    var th = this;
    var args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
}
// 节流:触发函数事件后,短时间间隔内无法连续调用,只有上一次函数执行后,过了规定的时间间隔,才能进行下一次的函数调用。
export function throttle(fn, interval) {
  var last;
  var timer;
  var interval = interval || 200;
  return function () {
    var th = this;
    var args = arguments;
    var now = +new Date();
    if (last && now - last < interval) {
      clearTimeout(timer);
      timer = setTimeout(function () {
        last = now;
        fn.apply(th, args);
      }, interval);
    } else {
      last = now;
      fn.apply(th, args);
    }
  }
}

2.在需要的页面引入

import { debounce, throttle } from "src/utils/utils";
method:{
  showCompleteTel: throttle(function() {
     //逻辑代码
    }, 2000),
}

点击事件的防抖和节流

原文:https://www.cnblogs.com/itcjh/p/12809113.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!