js函数防抖和函数节流

函数防抖(debounce):
input框点击搜索按钮只在最后一次进行搜索

	function debounce () {
		let timer = null
		return function () {
			clearTimeout(timer)
			timer = setTimeout(() => {
				console.log('开始搜索')
			},500)
		}
	}
	let btn = document.getElementById("btn")
	btn.addEventListener('click',debounce())

函数节流(throttle):
input框在防抖基础上特定时间间隔自动搜索一次

function throttle () {
	let pretime = null
	let time = 1000
	let timer = null 
	return function() {
		let now = +new Date()
		clearTimeout(timer)
		if(!pretime) pretime = now
		if((now - pretime) >= time){
			console.log('开始搜索')
			pretime = null
		}else{
			timer = setTimeout(() => {
				console.log('开始搜索')
			},500)
		}
	} 
}
let btn = document.getElementById("btn")
btn.addEventListener('click',throttle())

你可能感兴趣的:(js函数防抖和函数节流)