JavaScript函数的节流和防抖

废话不多说,简单粗暴,直接看

防抖:只执行最后一次(避免抖动)
节流:以恒定时间间隔执行,可能执行多次(减少次数)

//防抖
window.onresize = function(){
    debounce(fn,1000)
}
var fn = function(){console.log('--1--')}
var timer = null
function debounce(fn,timeLong){
	if(timer ){
	    clearTimeout(timer )//进来就把定时器删了
	    timer = ''
	}
	timer =setTimeout(function(){
		fn()
	},timeLong)
}
//节流
window.onresize = function(){
    throttle(fn,1000)
}
var fn = function(){console.log('--2--')}
var timer = null
function throttle(fn,timeLong){
	if(timer ) return;
	timer =setTimeout(function(){
	  fn();  //进来先放函数,再删定时器
	  clearTimeout(timer );
	  timer =null;
	},timeLong)
}

你可能感兴趣的:(JavaScript,javascript,前端,开发语言,vue.js,es6)