This is the 14th day of my participation in the More text Challenge. For more details, see more text Challenge


preface

Interviewer: Give me a hand-written shockproof and throttling.

I: 💥…


Image stabilization (debounce)

Shaking, as the name suggests, to prevent shaking, so as not to mistake one event for many times, tapping the keyboard is a daily exposure to the shaking operation.

To understand a concept, you must first understand the scenario in which the concept is applied. In the JS world, what is the scene of anti – shaking

  1. Buttons such as login and texting need to be stabilised to prevent users from clicking too quickly and sending multiple requests
  2. When resizing the browser window, the number of resize times is too frequent, resulting in excessive calculation. At this time, it needs to be in place once, which is used to stabilize
  3. The text editor saves in real time, when no changes are performed for one second

ClearTimeout (timer) clearTimeout(timer)

How it works: When triggered, clears the previous timer, regardless of whether it has been executed.

function debounce (f, wait) {
  let timer
  return (. args) = > {
    clearTimeout(timer)
    timer = setTimeout(() = >{ f(... args) }, wait) } }Copy the code

The throttle (throttle)

Throttling, as the name suggests, controls the flow of water. Control the frequency of events. For example, once every 1s, or even once every minute. This is similar to the Rate Limit controlled by the server and gateway.

  1. scrollEvent, calculate location information every second, etc
  2. The browser plays events, calculates progress every second, and so on
  3. Input box real-time search and send requests display a drop-down list, every second to send a request (can also do anti-shake)

The lock timer=timeout is applied to the lock timer

How it works: When a timer is triggered, it returns if it has already been triggered. Until the next periodic time range.

function throttle (f, wait) {
  let timer
  return (. args) = > {
    if (timer) { return }
    timer = setTimeout(() = >{ f(... args) timer =null
    }, wait)
  }
}
Copy the code

conclusion

  • Anti-shake: prevents jitter. Event triggering per unit time will be reset to prevent events from being triggered multiple times by friendly fire. The code implementation is reset in clearTimeout. Shaking can be compared to waiting for an elevator, as long as one person comes in, it needs to wait a little longer. In business scenarios, avoid repeated submission when the login button is clicked multiple times.
  • Throttling: Controls traffic. Events can be triggered only once per unit time, which is similar to the Rate Limit on the server. Lock timer=timeout; The timer = null. Throttling can be likened to going through a traffic light, every time you wait for a red light, you can go through a batch.