• js实现防抖函数和节流函数


    防抖函数(debounce)

    1. 含义:防抖函数指的是在特定的时间内没有再次触发,才得以进行接下来的函数运行;
    2. 用途:当window.onresize不断的调整大小的时候,为了避免不断的重排与重绘,可以用防抖函数设置在onresize完成后一段时间内不再有窗口大小变动,此时再进行dom的重排重绘;
    	function debounce(fun,delay){
    		var timer = null;
    		return function(){
    			if(timer !=== null){
    				clearTimeout(timer);
    			};
    			timer = setTimeout(fun,delay);
    		}
    	};
    	
    	function handler(){
    		console.log('hello')
    	};
    	
    	window.onresize = function(){
    		debounce(handler,1000);
    	};
    

    节流函数(throttle)

    1. 含义:在函数被调用成功后,短时间内不会被再次触发;
    2. 用途:当点击表单按钮的时候,能够有效的避免高频次的提交操作;
    	function throttle(fun.delay){
    		var flag = false;
    		return function(){
    			var _this = this;
    			var args = arguments;
    			if(flag){
    				return;
    			}else{
    				flag = true;
    				setTimeout(function(){
    					fun.apply(_this,args);
    					flag = false;
    				},delay);
    			}
    		}
    	};
    
    	function handler(){
    		console.log('world');
    	};
    
    	window.addEventListener('scroll',throttle(handler,1000));
    

    总结:

    • 相同防抖和节流函数都可以有效的减少短时间内触发同一函数的频次;
    • 不同的是 以百度首页的输入框自动提示搜索关联词功能为例
      • 防抖函数会确定在你输入完成后的一定时间(delay)去请求接口数据;
      • 节流函数会在你整个输入过程期间内,没过一定时间(delay)请求一次接口数据;
  • 相关阅读:
    Codeforces Round #564(div2)
    714
    1471
    UVa 11134
    UVa 1152 -4 Values whose Sum is 0—[哈希表实现]
    UVa 1374
    UVA 1343
    UVa 12325
    Yet Another Number Sequence——[矩阵快速幂]
    River Hopscotch-[二分查找、贪心]
  • 原文地址:https://www.cnblogs.com/7Ezreal/p/12051812.html
Copyright © 2020-2023  润新知