preface
Before we get started, let’s talk about a scenario that we often encounter during front-end development. Input box on the page there are usually used as the search data, and these data are often send requests to the backend access by the front end, if the user has been input in the input box, and then send the request will be kept, obviously this is not what we want to see the results, and the stabilization and throttling will be able to make optimization to this application scenario.
Image stabilization
Anti-shake: When an event is continuously triggered, the event handler is not executed immediately, but only executed once when the event is not triggered again for a certain period of time. If the event is triggered again before the set time, the timer is reset. Now simulate the process with the onMousemove event:
- Anti – shake is not used
If this is a request, it will be a large number of requests in a short period of time, affecting overall performance.2. Use the anti-shake function
So when the onMousemove is done for 1s, I’m going to execute print, and I’m going to use closures. If you don’t know, you can read my articleWhat is a closure?”
let num = 0;
// The buffeting function
function debounce(fn, delay){
let timer = null;
return function () {
if (timer){
clearTimeout(timer);
}
timer = setTimeout(fn, delay); }}function print(){
console.log("Executed" + ++num + "Time");
}
document.getElementById("box").onmousemove = debounce(print, 1000)
Copy the code
The throttle
Throttling: Ensures that event handlers are called only once in a certain period of time when events are continuously triggered. Events continue to fire, but instead of executing them all the time, we can set a fixed interval at which to execute them. The application scenarios mentioned in the preface are very suitable for throttling. This is used as an example to demonstrate throttling.
- Unused throttle
When throttling is not used, the event function is executed each time input is made.
2. Use throttling
The output is executed every second
let num = 0;
// throttling function
function throttle(fn, delay){
let timer = null;
let nextFlag = true; // Use the flag bit to determine whether an execution has ended
return function () {
if (nextFlag){
nextFlag = false;
timer = setTimeout(function () {
fn();
nextFlag = true; }, delay); }}}function print(){
console.log(Have been run `${++num}"Time,The ${document.getElementById("search").value}`);
}
document.getElementById("search").onkeydown = throttle(print, 1000)
Copy the code