Anti-shake & throttling

Input box anti – shake

What is anti-shake

The debounce policy is to delay the callback after an event is triggered for n seconds. If the event is triggered again within n seconds, the timer is reset.

Benefits: The callback is executed only once, but not frequently, when events are frequently triggered

Application scenarios of anti-shake

When you enter a string of characters in the input box, you can use the anti-shake policy to execute the query request only after the input is complete. In this way, the query request is effectively reduced

Less request times, saving request resources;

To achieve the input box shake – proof

  • Anti-jitter timer
  • Define anti – shake function, function inside the definition of a delay device, in the demo call launchJSONPThe request of
  • In the triggerkeyupEvent, immediately emptytimer, and then call the anti-shake function
Var timer = null // 1. Timer function debounceSearch(keywords) {// 2. Suggestlist (keyword)}, 500)} $('#ipt').on('keyup', function() { // 3. When the keyUp event is triggered, clear the timer clearTimeout(timer) immediately. Omit other code debounceSearch(keywords)})Copy the code

Cache a list of suggestions for searching

Define a global cache object

Var cacheObj = {}Copy the code

Save the search results to the cache object

  • The key is the keyword entered by the user, and the value is the value returned by the server
Function renderstList (res) {// suggestlist... Var k = $('#ipt').val().trim() cacheObj[k] = res} var k = $('#ipt').val().Copy the code

Get search suggestions from the cache first

  • Before making a request, determine if there is any data in the cache
/ / listen to the text frame's keyup event $(' # ipt) on (' keyup ', function () {/ /... Suggestlist (cacheObj[keywords])} // Get a search suggestion list from the cache debounceSearch(keywords) })Copy the code

The throttle

What is throttling (⭐⭐⭐)

Throttling, as the name suggests, reduces the frequency with which events occur over a period of time.

Application scenarios of throttling

(1) The mouse continuously triggers an event (such as click), only triggers once per unit of time;

(2) Lazy loading to listen to the position of the scroll bar, but do not have to slide triggered every time, can reduce the frequency of calculation, and do not have to waste CPU resources;

Throttling case Mouse following effect

UIThe effect

Apply colours to a drawingUIStructure and beautify the style

<! <img SRC ="./assets/angel.gif" Alt ="" id="angel" /> /* CSS style */ HTML, body {margin: 0; padding: 0; overflow: hidden; } #angel { position: absolute; }Copy the code

Mouse follow effect without throttling

  • Get image elements
  • registeredmousemoveThe event
  • Sets the position of the picture
$(function() {var angel = $('#angel'); $(document).on('mousemove', Function (e) {/ / $(angel) sets the position of the picture. The CSS (' left ', e.p ageX + 'p'). The CSS (' top ', e.p ageY excuse + 'p')})})Copy the code

The concept of a throttle valve

Whether the toilet of high-speed railway is occupied or not is controlled by the traffic light. The red light means occupied and the green light means available.

Assuming that it takes five minutes for everyone to go to the bathroom, the occupied bathroom cannot be used by anyone else within five minutes.

After the previous person has finished using the bathroom, the red light needs to be reset to green, indicating that the next person can use the bathroom.

Before the next person goes to the bathroom, they need to check whether the control light is green to see if they can go to the bathroom.

If the throttle valve is empty, the next operation can be performed. If the value is not empty, the next operation cannot be performed.

After the current operation is complete, the throttle valve must be reset to empty, indicating that the next operation can be performed.

Check whether the throttle valve is empty before each operation.

Optimize mouse following with throttling

  • Pre-define a Timer throttle
  • When the mouse following effect is set, the timer throttle valve is cleared for the convenience of opening the delay device next time
  • Check whether the throttle valve is empty when the event is executed. If it is not empty, the interval between the last execution is less than 16 milliseconds
$(function() { var angel = $('#angel') var timer = null // 1. $(document). On ('mousemove', function(e) {if (timer) {return} // 3. Determine whether the throttle valve is empty. If not, Timer = setTimeout(function() {$(angel).css('left', e.pagex + 'px').css('top', e.pageY + 'px') timer = null // 2. When the mouse following effect is set, empty the timer throttle valve for the convenience of starting the delay device next time}, 16)})Copy the code

Summarize the difference between anti-shake and throttling

  • Anti – shake: If the event is triggered frequently, anti – shake can ensure that only the most trigger takes effect! The previous N triggers will be ignored!
  • Throttling: Throttling can reduce the frequency of event firing if the event is fired frequently, so throttling is selectively executing a portion of the event!