JS实现/封装节流函数

封装节流函数

节流原理:在一定时间内,只能触发一次

let timer, flag;
/**
 * 节流原理:在一定时间内,只能触发一次
 * 
 * @param {Function} func 要执行的回调函数 
 * @param {Number} wait 延时的时间
 * @param {Boolean} immediate 是否立即执行
 * @return null
 */
function throttle(func, wait = 500, immediate = true) {
	if (immediate) {
		if (!flag) {
			flag = true;
			// 如果是立即执行,则在wait毫秒内开始时执行
			typeof func === 'function' && func();
			timer = setTimeout(() => {
				flag = false;
			}, wait);
		}
	} else {
		if (!flag) {
			flag = true
			// 如果是非立即执行,则在wait毫秒内的结束处执行
			timer = setTimeout(() => {
				flag = false
				typeof func === 'function' && func();
			}, wait);
		}
		
	}
};
export default throttle

使用

// 按钮点击
    click(e) {
      // 进行节流控制,每this.throttle毫秒内,只在开始处执行
      throttle(() => {
        // 如果按钮时disabled和loading状态,不触发水波纹效果
        if (this.loading === true || this.disabled === true) return;
        // 是否开启水波纹效果
        if (this.ripple) {
          // 每次点击时,移除上一次的类,再次添加,才能触发动画效果
          this.waveActive = false;
          this.$nextTick(function() {
            this.getWaveQuery(e);
          });
        }
        this.$emit('click', e);
      }, this.throttleTime);
    },

你可能感兴趣的:(uniapp,VUE开发,javascript,前端,java)