This is the 16th day of my participation in the August Text Challenge.More challenges in August

Question origin

Page common listening browser scroll events, window onresize Events and real-time monitoring of input events by the input box will lead to these events being triggered at a high frequency. If the execution function of such events is complex and the response cannot keep up with the triggering of events, the page will be stuck in suspended animation, which will make the user experience very bad and the browser performance is limited. This should not be wasted, so the strategy of function debounce and function throttling emerged

The solution to the problem

  • Function debounce: When the event is triggered, set a period to delay the execution of the action. If the event is triggered again, reset the period until the end of the period to execute the action.
  • Leading edge image stabilization: Perform the action before, and then set the cycle, within the cycle events are triggered, do not perform the action, and the cycle is reset.
  • Function throttling: Within a fixed period, only one action is performed. If a new event is triggered, the action is not performed. After the cycle ends, another event is triggered to start a new cycle.note: Delay: The action is executed after the period ends. Leading edge: Start the cycle after the action is performed

Application scenarios

  • Function debounce: Event triggering is high frequency but has pauses, such as page resize events
  • Function throttling: Events are triggered frequently and continuously, for example, listening for browser scroll events

Implementation method

Function debounce(fn, wait) {var timer = null; return function() { if (timer) clearTimeout(timer); timer = setTimeout(() => fn.apply(this, Array.prototype.slice.call(arguments, 0)), wait); Function throttle(fn, wait) {var timer = null; var timer = null; var timer = null; return function() { if (! timer) { timer = setTimeout(() => { fn.apply(this, Array.prototype.slice.call(arguments, 0)); timer = null; }, wait); }}}Copy the code

(For attention)

Welcome to follow my official account: Class A Coder and get daily dry goods push. Thank you again for reading. I’m Han the Programming Monkey