Image stabilization
- Usage scenario: The command is not executed immediately. Listen to the scrollbar event within a certain time (1000ms), if triggered again, first cancel the timer, and then restart the timer; If not triggered again, execute
The throttle
- Usage scenario: Flag is used to indicate whether the last triggering is complete
Other Usage Scenarios
- Input Field real-time search
code
- Take the scroll bar event as an example
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="Width = device - width, initial - scale = 1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<style type="text/css">
.scoll{
width:100%;
height: 120vh;
}
</style>
<body>
<div class="scoll">
vuvuvuuvuvu
</div>
<script type="text/javascript"< span style = "box-sizing: border-boxfunction debounce(fn, delay){
let timer = null;
return function() {if(timer){
clearTimeout(timer)
}
timer = setTimeout(fn, delay)}} // Throttling functionfunction throttle(fn, delay){
let valid = true
return function() {if(! valid){return false
}
valid = false
setTimeout(() => {
fn();
valid = true
}, delay)
}
}
function showTop() {/ / Google: document. The body. The scrollTop Internet explorer, firefox: document. The documentElement. The scrollToplet scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('Scroll bar position:'+ scrollTop); Window. onscroll = throttle(showTop, 1000) </script> </body> </ HTML >Copy the code