Function anti-shake and throttling

Function stabilization and function throttling: Is a means to optimize frequently executed JavaScript code. Commonly used in JavaScript for some events, such as browser resize, scroll, mouse mousemove, mouseover, keyboard keypress, input, etc. For example, when the input event of the input box is triggered, the callback function bound to the event is constantly called, which greatly wastes resources and reduces front-end performance. To optimize the experience, you need to limit the number of calls to these events.

Function image stabilization

The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the timer is reset.

Original version:

Let timer // For convenience, Document.body. onscroll = function () {if(timer){// clearTimeout(timer); } timer = setTimeout(function () {console.log()}, delay); }Copy the code

Packaged version:

function debounce(fn, Let timer return function () {if (timer) {clearTimeout(timer); } timer = setTimeout(function () { fn.apply(_this,arguments) }, delay); }}Copy the code

Function of the throttle

Execute the function only once in a set period of time (minimum interval).

Original version:

Let gapTime = delay// let lastTime = // let nowTime = // let fn = () => console.log(' I did it ') Document.body.onscroll = () => {nowTime = date.now () // Get the current time // If (! lastTime || nowTime - lastTime > gapTime) { fn() lastTime = nowTime } })Copy the code

Packaged version:

function throttle(fn, gapTime) { let lastTime let nowTime return function (){ nowTime = Date.now() if (! lastTime || nowTime - lastTime > gapTime) { fn() lastTime = nowTime } } }Copy the code

Common Application Scenarios

Application scenarios of function anti-shake

Sequential events that only need to trigger a callback are:

  • The search box searches for input. The user only needs to type one last time before sending the request
  • Mobile phone number, email verification input detection
  • Window size Resize. Just after the window adjustment is complete, calculate the window size. Prevent repeated rendering.
Application scenarios of function throttling

The scenarios in which a callback is executed at an interval are:

  • Scroll to load, load more or roll bottom to listen
  • Google search box, search association function
  • Click submit frequently, and the form is submitted repeatedly

The purpose of this article is to understand the principle of function anti-shake and function throttling, so it only introduces the original implementation method, you can also modify the original version, packaging, to use in the production environment.