当前位置:网站首页>Anti shake and throttling of JS

Anti shake and throttling of JS

2022-07-23 11:18:00 Vivqst

Shake proof : High frequency triggered events , After triggering the event n Execute the function once per second , if n Second event triggers again , Then restart the calculation of time
Use scenarios : Query while entering the search box , Optimized query , Query after input stops

function debounce(fn, delay) {
    
	var timeout = null
	return function(){
    
		if(timeout) clearTimeout(timeout)
		timeout = setTimeout(() => {
    
			//  Change in strict mode this The direction of 
			fn.apply(this, arguments)
		}, delay)
	}
}

function handle() {
    
 	console.log(' Execution event ')
}

window.addEventListener('scroll', debounce(handle, 1000))

throttle : High frequency triggered events , every other n Execute the function once per second , Dilutes the frequency of executing the function
Use scenarios : Listen for scrollbar scrolling Events , When scrolling, add some styles or animation effects to the elements according to the height of scrolling

function throttle(fn, delay) {
    
	var timeout = null 
	return function(){
    
		if(timeout) return false
		timeout = setTimeout(() => {
    
			fn.apply(this, arguments)
			clearTimeout(timeout)
         	timeout = null
		}, delay)
	}
}

function handle() {
    
	console.log(' Execution event ')
}

window.addEventListener('scroll', throttle(handle, 1000))
原网站

版权声明
本文为[Vivqst]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207230537430076.html