Anti-shake and throttling

Debounce

Anti-shake is to trigger a large number of the same thing in a short period of time, and only trigger once;

function debuonce(fn, delay){
    
    
  let timer = null;
  return function() {
    
    
    if(timer) {
    
    
		clearTimeout(timer) // 将上一次的清除掉
	}
	timer = setTimeout(fn, delay); // 然后重新计时  
  }
}

transfer

function log(){
    
    
	console.log(2)
}

window.onscroll = debounce(log, 2000)

Throttle

If the scroll event is triggered continuously within a limited time, as long as it keeps on, it will never output console.log(2)

If the demand is to print out 2 at intervals, but not so frequently, throttling is used.

function throttle(fn, delay){
    
    
	let valid = true;
	return function(){
    
    
     if (!valid) {
    
     // 休息时间
		return false;
	  }
	  // 工作时间了
	  valid = false;
	  setTimeout(() => {
    
    
		valid = true;
		fn();	
	  }, delay)
    }

}

function log(){
    
    
	console.log(2)
}

window.onscroll = throttle(log, 2000)
// 这样就是 持续滚动,但是会间隔2秒输出

Guess you like

Origin blog.csdn.net/Beth__hui/article/details/114047903