js函数节流+防抖

节流:
懒加载、滚动加载、加载更多或监听滚动条位置;
百度搜索框,搜索联想功能;
防止高频点击提交,防止表单重复提交;
//节流函数,只有大于设定的周期才会执行第二次

  function throttle (func, duration) {
    
    
      let last = 0
      return function () {
    
    
           let now = Date.now()
           if (last && (now - last) < duration) return
           last = now
           func.apply(this, arguments)
      }
  }

  var aa = function(a,b){
    
    
    console.log(a+b)      
  }

  var bb = throttle(aa, 30)

  bb(2, 3)

防抖:
搜索框搜索输入。只需用户最后一次输入完,再发送请求;
用户名、手机号、邮箱输入验证;
浏览器窗口大小改变后,只需窗口调整完后,再执行 resize 事件中的代码,防止重复渲染。
//防抖函数,在规定时间内只让最后一次生效

	function debounce(fn, delay) {
    
    
		let timer = null;
			return function() {
    
    
				clearTimeout(timer); //清除前一次的事件触发
				timer = setTimeout(() => (
					func.apply(this, arguments)
				), delay); //重新设置定时触发事件
			}
	}
	var bb = function(a,b){
    
    
	    console.log(a+b)
	}
	
	bb = throttle(aa, 30)
	
	(2, 3)

猜你喜欢

转载自blog.csdn.net/weixin_45685252/article/details/105973901