What is function stabilization?
When making the associative words in the search box, relevant associative words will be obtained according to the content entered by the user. If there is no function to prevent shaking, the picture below will appear
Frequent triggering of input events and frequent data interaction with the background wastes performance and leads to anti-shake
How should anti – shake be used?
Simply put, anti – shake is a delay timer
Add a delay device before the user input and send the request a few milliseconds after the user input. Only the user input last time, simple optimization of the code, can achieve the goal belowCopy the code
<body>
<input type="text">
<script>
let ipt = document.querySelector('input');
let timer = null;
ipt.oninput = function(){
timer && clearTimeout(timer) ;
timer = setTimeout(() = >{
console.log(this.value);
},500)}</script>
</body>
Copy the code
You can already achieve the effect of shaking, next to encapsulate
<body>
<input type="text">
<script>
let ipt = document.querySelector('input');
ipt.oninput = debounce(function(){
// Business code dosomting
console.log(this.value);
},500);
function debounce(fn,delay){
let timer = null;
return function(){
timer && clearTimeout(timer) ;
timer = setTimeout(() = >{
// This refers to the window and calls the call method to the input
fn.call(this)
},delay)
}
}
</script>
</body>
Copy the code
This uses the call method, as detailed in my other article
To use it in vue, put the code above it in your tool js file and import it into the call