How to understand anti-shake and throttling

1. Anti-shake

Definition of anti-shake: After the event is triggered, the callback function will be executed after a delay of n seconds. If the event is triggered again within this n seconds, the timing will be restarted, and only the last trigger will be executed.

what? Confused! It doesn't matter, here is a little joke, you should understand it in seconds after reading it:

Xiao Ming's military training, the instructor issued an order: turn left! turn right! turn back! Everyone followed suit, only Xiao Ming sat down to rest, and the instructor was angry with a group of them, asking him loudly why he didn't obey the command? Xiao Ming said, I am going to wait for you to figure out which direction to turn, and then I will turn.

Although it is a joke, it is a good illustration of the definition of anti-shake: give a fixed time, if you start to trigger the action, and there is no more action within this fixed time, I will execute it once, otherwise I will start again every time timing.

We can understand it in terms of corner cases: if the given time interval is large enough, and actions are fired all the time, then the callback will never be executed. In the context of the joke, Xiao Ming will only switch after the instructor issues the number for the last time.


2. Throttling

Definition of throttling: Callbacks will not be triggered repeatedly within the specified interval time range, and callbacks will only be triggered if the time interval is greater than this time interval, turning frequent triggers into a small number of triggers.

If you understand anti-shake and throttling, it will be easier to understand

When a student is in a self-study class, the head teacher will come to inspect once every five minutes. You can do whatever you want within five minutes. It’s okay if the roof is lifted. As long as you don’t get caught by the head teacher at the five-minute interval, if you can’t catch it, it’s nothing , If you catch her, she will fuck you.

That is, the user will repeatedly trigger some operations, such as mouse movement events. At this time, you only need to specify a "tour" interval time. No matter how many times the user triggers during the period, the given callback function will only be executed at the interval point.

We can also use extreme cases to understand: if the given interval is 100 milliseconds, and the user moves the mouse crazily on the screen without interruption, then your callback function will be at 100 milliseconds, 200 milliseconds, 300 milliseconds... Just carry on like this.

Guess you like

Origin blog.csdn.net/laya1211/article/details/126747758