前端开发 节流和防抖

1、防抖

常见案例:用户搜索框连续输入时,当用户停止输入后获取查询结果。
	// 防抖
	function debounce(fn, delay=500) {
		let timer = null;
		return function(){
			if (timer){
				clearTimeout(timer)
			}
			timer = setTimeout(() => {
				fn.apply(this, arguments);
            	timer = null;
			}, delay)
		}
	}

2、节流

常见案例:轮播图左右滑动按钮,500ms内频繁点击,只允许触发一次滑动事件,避免图片滑动过快。

	// 节流
	function throttle(fn, delay=500) {
    	let endTime= 0;
	    return function() {
	        var nowTime = new Date(),
	        	_self = this,
	        	args = arguments
	        if (nowTime - endTime > delay) {
	            fn.apply(_self, args);
	            endTime = nowTime
	        }
	    }
    }

你可能感兴趣的:(原生javascript,utils,js,节流,防抖,优化)