Throttling and Debounce in JS

1. Anti-shake

  • Concept: It refers to triggering events continuously but only executing the last time within a set period of time. For example: set 1000 milliseconds to execute, when you trigger an event, it will be executed after 1000 milliseconds, but if you trigger the event again when there are 500 milliseconds left, it will restart after 1000 milliseconds
  • Core: start over
  • Application scenarios: 1. Search input in search box 2. Real-time saving in text editor
  • Code implementation idea:
let timerId = null;
document.querySelector('.ipt').onkeyup = function(){
    
    
	//防抖
	if(timerId !== null){
    
    
		clearTimeout(timerId)
	}
	timerId = setTimeout(() => {
    
    
		console.log("防抖函数")
	},1000)
}

2. Throttling

  • Concept: It refers to the continuous triggering of events but the function is only executed once in a set period of time. For example: if you set the execution to 1000 milliseconds, then you trigger multiple times at 1000 milliseconds, and only execute it once after 1000 milliseconds
  • Core: don't interrupt
  • Application scenarios: 1. High-frequency events (quick mouse click and slide) 2. Pull-down loading 3. Video playback record time
  • Code implementation idea:
let timerId = null;
document.querySelector('.ipt').onmouseover= function(){
    
    
	//节流
	if(timerId !== null){
    
    
		return
	}
	timerId = setTimeout(() => {
    
    
		console.log("节流函数")
		timerId = null;
	},100)
}

Guess you like

Origin blog.csdn.net/Macao7_W/article/details/128097768