所谓的防抖节流函数

// 防抖 函数
// 函数防抖(debounce):触发高频事件后n秒内函数只会执行一次,如果n秒内高频事件再次被触发,则重新计算时间。
export const debounce = (fn, delay = 300)=> {   //默认300毫秒
    var timer;
    return function() {
        var args = arguments;
        if(timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(this, args);   // 改变 this
        }, delay);
    };
}

// 节流
// 函数节流(throttle):高频事件触发,但在n秒内只会执行一次,所以节流会稀释函数的执行频率。
export const throttle = (fn, delay, mustRun) => {
	var timer = null, previous = null;
	return function () {
		var now = +new Date(), context = this, args = arguments;
                //过去的时间不存在的时候 将现在的时间赋值
		if (!previous ) previous = now;
                //获取时间差
		var remaining = now - previous;
		if (mustRun && remaining >= mustRun) {
			fn.apply(context, args);
			previous = now;
		} else {
			clearTimeout(timer);
			timer = setTimeout(function () {
				fn.apply(context, args);
			}, delay);
		}
	}
}
posted @ 2020-07-04 11:19  hello蔚蓝  阅读(165)  评论(0)    收藏  举报