防抖debounce和节流throttle实现

防抖多用于用户注册校验用户名重复等操作

function debounce(){
		let timer = null;
		return function(){
			clearTimeout(timer);
			timer = setTimeout(()=>{
				//do something here
				console.log('check ok!')
			},500)
		}
	}
	var checkPost = debounce()

节流多用于优化性能,例如随鼠标滚动驱动的行为可适当减少行为密集度

function throttle(){
		let timer = null;
		return function(){
			if(!timer){
				timer = setTimeout(()=>{
				//do something here
				console.log('optimized!');
				clearTimeout(timer)
				timer = null
			},1000)
			}
		}
	}
	var rerender = throttle()

你可能感兴趣的:(前端,算法)