preface
At the beginning of contact with these two concepts, I do not quite understand the semantics of these two words, and do not know exactly what they are used for. I’m sure a lot of people are like me, if not, it would be embarrassing.
Disclaimer: This title is intended to get you to forget the concept, to introduce what you can do in what situation from a business scenario, not to get caught up in the two terms, not to learn for the sake of learning. It’s not that you should forget the substance of the two concepts, there’s no need to forget.
Function image stabilization
Forget function stabilization for a moment.
With requirements followed by solutions, let’s describe a simple business scenario:
Now we need to implement a cloud cache function for articles. If the user calls the interface synchronous cache for each character input, the server will be under great pressure.
In addition, multiple interfaces are sent in sequence, and the server may not receive them in this order, which may result in the stored content is not the latest.
Instead of calling the interface every time, choose a time when the user stops typing.
So how do we know the user has stopped typing?
If the contents of the input box do not change in N seconds, we can assume that the user has stopped typing or paused typing.
let timer;
const input = document.querySelector('input');
input.addEventListener('input'.function() {
clearTimeout(timer);
timer = setTimeout(function() {// execute specific code}, 500)})Copy the code
See demo:
It is observed that when nuggets publish articles, automatic save to the draft function is also a similar implementation method, you can try
Function of the throttle
Forget function throttling for a moment.
To describe a simple business scenario:
Now to implement a “like” function, a user posted a dynamic, everyone can give him unlimited “like”, that is to say, every “like” should be recorded on the back end. Theoretically, a user can call the interface once for every like. But again, as above, this will put a lot of pressure on the server.
Unlimited likes means that each click of a user is a valid like, which needs to be accumulated. We’re going to create a likes list, ranking it by the number of likes per user.
This can be mitigated by limiting the frequency of a button click to 300 milliseconds before calling the interface, during which all clicks are accumulated.
/ / thumb upletlikes = 0; // Timer idlettimer; /* * The user likes the function * */function clickButton() {
likes++;
if ( timer ) return;
timer = setTimeout(() => {// Perform network request // Ajax... // Likes = 0; // Reset timer timer = null; }}, 300)Copy the code
See demo:
conclusion
This kind of technical solution for dealing with certain situations is not so important for terminology, it’s basically just for communication where everybody knows what’s being said.
The key is to know why you’re doing it in the first place.