js防抖节流

135 阅读1分钟

js防抖

在用户输入内容之前加上延时器在用户输入完毕之后的几毫秒再去发送请求,只需要用户输入的最后一次内容, 简单的对代码进行优化,就可以实现下图的目标

	function debounce(fn, time) {
		let _arguments = arguments
		let timeout = null
		return function() {
			if (timeout) {
				clearTimeout(timeout)
			}
			timeout = setTimeout(() => {
				fn.call(this, _arguments)
			}, time);
		}
	}

js节流

控制高频事件执行次数

var throttle = function(func, delay) {            
    var timer = null;            
    return function() {                
        var context = this;               
        var args = arguments;                
        if (!timer) {                    
            timer = setTimeout(function() {                        
                func.apply(context, args);                        
                timer = null;                    
            }, delay);                
        }            
    }        
}