JavaScript 防抖 && 节流

函数防抖和节流都是为了防止一个函数被无意义的高频率调用。
多次触发事件,防抖只会执行最后一次;节流会隔一段时间执行一次。

防抖

防抖是指,某些代码不可以在没有间隔的情况下连续执行。第一次调用函数,创建一个定时器,在指定的时间间隔之后运行代码。当第二次调用函数是,清除前一个定时器并设置另外一个。

如果前一个定时器已经执行,那么这个操作就没有什么意义。然而,如果前一个定时器尚未执行,那就是将其替换成一个新的定时器。目的是只有在执行函数的请求停止了一段时间之后在执行。

基本模型:

	var processor = {
        timeoutId: null,
		//实际进行处理的方法 
		performProcessing: function(){
			//实际执行的代码 
		},
		//初始处理调用的方法 
		process: function(){
            clearTimeout(this.timeoutId);
            var that = this;
            this.timeoutId = setTimeout(function(){
                that.performProcessing();
            }, 100);
		} 
	};
	//尝试开始执行 
	processor.process();

优化:

	function throttle(method,context){
        clearTimeout(method.timer)
        method.timer = setTimeout(function(){
            method.call(context)
        },500)
    }

节流

节流就是让函数在特定的时间执行一次。

	// 函数节流
	var canRun = true;
	document.getElementById("throttle").onscroll = function(){
	if(!canRun){
	  return
	}
	canRun = false
	setTimeout( function () {
	    console.log("函数节流")
	    canRun = true
	  }, 500)
	}

猜你喜欢

转载自blog.csdn.net/weixin_42186513/article/details/83617685