Throttling and anti-shaking
These two things, you’ve heard of them, are two ways to optimize browser performance. You must have read the relevant article, if still not quite clear, no matter, after reading this essay, I believe you can easily understand the difference.
Deounce
Let’s talk about anti-shaking first, and here’s a little joke that should make you understand in seconds:
Xiaoming military training, instructors issued orders: turn left! Turn right! Turn back! Everyone did, only Xiaoming sat down to rest, the instructor fire of a group, loudly scolded him to ask why he did not listen to the command? Xiao Ming said, I am ready to wait for you to think about which direction to turn, I turn again.
It’s a joke, but it’s a good example of the definition of anti-shake: Give it a fixed time, and if you start triggering the action and there’s no more action within that fixed time, I’ll do it once, otherwise I’ll start the timer again every time. We can think of it in an extreme case: if a given interval is large enough and an action is fired all the time, the callback will never execute. In the context of a joke, xiao Ming will turn only after the instructor gives the number for the last time.
Throttle
If you understand the anti-shake, the throttling, it’s a lot easier to understand
Students on self-study class, the teacher in charge five minutes come to patrol once, within five minutes literally you how skin, the roof lifted all right, as long as you don’t in five minutes of time interval point was caught by the teacher in charge, not caught when did not happen, caught she will get you.
Here, the homeroom teacher is the throttle; You mess up, it’s user-triggered events; When you are caught by the class teacher, you are executing the callback function.
Throttling definition: When the user repeatedly triggers some action, such as a mouse movement event, you only need to specify an interval of “walk”, no matter how many times the user triggers, only the given callback function will be executed at the interval point. We can also use the extreme case: if the given interval is 240 milliseconds and the user keeps frantically moving the mouse around the screen forever, your callback will be 240 milliseconds, 480 milliseconds, 720 milliseconds… And so it goes on
What are these two for?
- Deounce:
- Can be used for input.change real-time input verification, such as input real-time query, you can not press a word to go to the back end of a check, must be to enter a string, unified to query a data.
- Can be used towindow.resizeEvents, such as window scaling, are recalculated
DOM
size
- Throttle, for listening
mousemove
, mouse scrolling, etc., usually used for:Drag and drop the animation,The drop-down load.
Throttling is usually used in more frequent scenarios than shake-refresh, and is mostly for operations that involve animation.
Talking is cheap show me the code
Image stabilization
function debounce (fn, delay = 200) {
let timeout;
return function() {
// reset the timer
timeout && clearTimeout(timeout);
timeout = setTimeout(fn.bind(this), delay, ...arguments);
}
}
const handlerChange = debounce(function () {alert('Update triggered')})
// Bind listener
document.querySelector("input").addEventListener('input', handlerChange);
Copy the code
The throttle
function throttle (fn, threshhold = 200) {
let timeout;
// Calculate the start time
let start = new Date(a);return function () {
// Trigger time
const current = new Date() - 0;
timeout && clearTimeout(timeout);
// If the interval point is reached, a callback is performed
if (current - start >= threshhold) {
fn.call(this. arguments);// Update the start time
start = current;
} else {
// The guarantee method will be executed once after the escape event
timeout = setTimeout(fn.bind(this), threshhold, ... arguments); }}}let handleMouseMove = throttle(function(e) {
console.log(e.pageX, e.pageY);
})
// Bind listener
document.querySelector("#panel").addEventListener('mousemove', handleMouseMove);
Copy the code
From the code, it is not difficult to find that throttling is just a judgment of time difference added on the basis of anti-shaking, wearing a vest.
Little brother, do you still have many question marks?
-
I can understand why anti-shaking is used for input.change. Why can’t mouse-drag function be used for anti-shaking? What happens if you do?
Think about it carefully, in simple terms, anti shake is actually only triggered once, obviously can not be used in this drag scene, if you use it, there will be a user dragged the box it does not move, after a while “snap” to jump over. In this case, the boss will buy you tea.
-
Throttling code, why add setTimeout? What happens if I don’t?
The main purpose of this code is, in plain English, to ensure that your callback will be executed once, no matter what. Use the mouse drag and drop function as an example. This solution solves the problem that the drag and drop function does not move at a high speed. It also ensures that when you finally drag and drop the mouse, the bounce can return to the position of your mouse, which is written in the code comment: ensure that the method is executed again after leaving the event.
In fact, these two questions are what I was confused about when I first saw anti-shake and throttling. I hope they can also help you.
Go a little deeper
I didn’t write this post, but a friend in the comments section pointed out the problem with throttling functions, and I learned some more details about anti-shock and throttling.
We can start with the above throttling function. Can you see what the problem is? This is also pointed out by my friend in the comment section: this throttling function will not execute immediately for the first time, but will wait for a period of time to execute, and the longer the wait time, the more obvious the delay. Let’s use this idea to look at the anti-shake function, the same problem.
So what’s the solution? For anti-shake and throttling, there are two versions: immediate and non-immediate. The non-immediate version is written above. To solve the above problem, it is easy to change the function and use the immediate version ~ only need to change the code line. (Throttling is similar, too.)
// The buffeting function executes immediately
function debounce (fn, delay = 200) {
let timeout;
return function() {
// If timeout == null, this is the first time, execute the callback directly, otherwise retry the timer
+ timeout == null ? fn.call(this. arguments) : clearTimeout(timeout); timeout = setTimeout(fn.bind(this), delay, ...arguments);
}
}
const handlerChange = debounce(function () {alert('Update triggered')})
// Bind listener
document.querySelector("input").addEventListener('input', handlerChange);
Copy the code
visualization
If you still can’t feel the difference, enter the portal
This article has been included in the front-end interview Guide column
Relevant reference
Zhihu: function anti – shake and function throttling article is written by Stuart Zhengmei, I would like to remember the big guy with technology.
conclusion
I’ve read a lot of commentary on the concepts of throttling and anti-shaking, and to be honest, very few articles really make it clear. Basically, it is a combination of official language and code flow. They all say that Talking is cheap show me the code, but in many cases, the Fucking code is so difficult, talk to me please. Really can let a person suddenly see, should be plain English.
Sincerely hope that this article can help you, to help a thumbs up, thank you!