[JavaScript] The difference and usage of anti-shake and throttling

1. Debounce

Meaning: The action will be executed only after n milliseconds have passed. If this action is called again within n milliseconds, the execution time will be recalculated

const debounce = (fn,waitTime)=>{
    
    
	let timer=null;
	return function(){
    
    
		clearTimeout(timeout)
		timeout=setTimeout(()=>{
    
     
			//如果fn 没有返回一个函数,则 fn.apply 报错
			fn.apply(this,arguments)  //arguments为fn 函数所需参数,apply()接收参数为Array类型
		},waitTime)
	}
}

use:

function add(a,b){
    
     
	 return function(){
    
    //返回一个函数
        console.log(a+b)
     }
}

window.onresize=debounce(add(2,3),500) 

//或者直接
// window.onresize=debounce(function(){
    
    
//     console.log('1111')
// },500)

Wrong wording:

function log(){
    
    
	console.log('1')//错误写法,没有返回匿名函数,报错 Cannot read property 'apply' of undefined
}
window.onresize=debounce(log(),500)//只输出一次

scenes to be used:

  • Save request resources when typing search queries in the input box
  • The resize event of the window object
  • Mousemove event when dragging

2. Throttling (throttle)

Meaning: pre-set an execution cycle, when the time of calling an action is greater than or equal to n, the action will be executed, and it will only be executed once within n milliseconds, and then enter the next new cycle

const throttle = (fn,time)=>{
    
    
	let flag=true;
	return function(){
    
    
		if(!flag) return;
		flag=false;
		setTimeout(()=>{
    
    
			fn.apply(this,arguments)
			flag=true
		},time)
	}
}

use:

window.onscroll = throttle(function(){
    
    
	console.log('正在加载中~')		
},3000) 

scenes to be used:

  • Throttling is often used to trigger continuous mouse clicks and monitor scroll events.

The difference between anti-shake and throttling

1. Common points:

Function throttling (throttle) and function debounce (debounce) are both to limit the execution frequency of the function, in order to optimize the response speed caused by the function trigger frequency being too high, and the response speed cannot keep up with the trigger frequency, resulting in delays, suspended animations or jams.

2. Difference:

Insert picture description here

throttleLike the cooling time of the button, to prevent users from clicking the button madly to submit the form and constantly calling the interface, we limit the request to be sent once every 2 seconds, no matter how many times you click;
debouncelike the query in the search box, wait for the user to complete the operation before executing, avoid typing During the period of constant inquiries.

reference:

Function throttling and function anti-shake

Anti-shake and throttling

Guess you like

Origin blog.csdn.net/iChangebaobao/article/details/108979424
Recommended