purpose
The following scenarios are often triggered by events frequently, so heavy behaviors such as DOM operations and resource loading are frequently performed, resulting in UI pauses and even browser crashes.
window
Objectresize
,scroll
eventmousemove
Event when dragging- Shooting game
mousedown
,keydown
event - Text input, automatic completion
keyup
events
In fact, for window resize
events, the actual demand is mostly to stop the n
subsequent processing after changing the size for milliseconds; while most other events require subsequent processing to be performed at a certain frequency. In response to these two requirements, two solutions, debounce and throttle, have emerged.
Throttle (also known as throttling) and debounce (also known as debounce) are actually function call frequency controllers.
debounce
When you call the function n
after the second, before the action is performed, if at this n
time and re-calculate the execution time and within seconds before calling the function will be canceled, cite a simple example, we do want to suggest based on user input, every time the user presses You can cancel the previous time when you press the keyboard, and you only care about the time of the last input.
throttle
Throttle restricts the calling frequency 1s
of a function within a certain threshold, for example , a function cannot be called twice.
The following is a practical demonstration
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="btn">点击</button>
</body>
<script>
// 防抖
function fangdou(fn,d){
var delay = d || 600
var timer ;
return function(){
var _this =this ;
var arg =arguments;
if(timer){
clearTimeout(timer)
}
timer =setTimeout(function(){
timer =null;
fn.apply(_this,arg)
},delay)
}
}
function jieliu(fn,d){
var delay = d || 600
var timer;
var last;
return function(){
var _this =this ;
var arg =arguments;
var now = +new Date();
if(last && now-last <delay){
clearTimeout(timer);
timer = setTimeout(function() {
last = now;
fn.apply(_this, arg);
}, delay);
}else{
last = now
fn.apply(_this, arg);
}
}
}
// 时间戳
// btn.onclick=function(){
// console.log(111)
// }
// btn.onclick=fangdou(function(){
// console.log(111,this)
// },500)
btn.onclick=jieliu(function(){
console.log(111,this)
},1000)
</script>
</html>