Debounce stabilization

Jitter prevention (forcing a function to be executed only once in a continuous period of time, even though it would have been called multiple times)

For example, if you trigger Mousemove in a row for 2 seconds, the browser will trigger hundreds of related events, and if you don’t use anti-shake, it will have a big impact on the user experience

Implementation approach

Debounce returns a closure that will still be called continuously and frequently, but inside the closure limits the execution of the original function fn, forcing it to execute only once after the continuous operation has stopped.

/** * @param fn (function) * @param delay(number) * * return (function) {function _debounce(fn, delay) {// SetTimeout var timer;  // Returns a function that executes if (typeof fn! = "function" || typeof delay ! = 'number') { // alert(fn); return; } return function() {var _this = this var args = arguments} return function() {var _this = this var args = arguments To ensure that fn clearTimeout(timer) // is not executed when the returned function has been called for the last time (i.e. when the user has stopped a continuous operation), Fn timer = setTimeout(function() {fn.apply(_this, args)}}Copy the code

Using mousemove as an example, let’s see how this function is used

<script> var temp = document.getElementById('mycarousel'), lis = temp.getElementsByTagName('li'); for (var i = 0; i < lis.length; I ++) {lis[I].onmousemove = _debounce(function(e) {// Trigger console.log(1)}, 2000)} </script>Copy the code

After using

Before using

In the scenario of real-time retrieval in the input box, ajax requests are sent to the server after real-time monitoring of user input data through the input change event. However, in the browser input box, events are penalized at a high rate, even at the user’s normal input speed. Sending requests at this high rate is a waste of resources and increases the strain on the server.

This is where debounce comes in handy, after the user has paused typing for a while before sending the request.

Input.addeventlistener ('onchange', _debounce(function(e) {// send ajax request console.log(1)}, 100), false);Copy the code

Throttle (throttle)

Throttle, when consistently firing events, consolidates events for a certain amount of time and actually fires an event at the end of that time (fixed rate of function execution)

Implementation approach

Compared to Debounce, there is no more than an extra time interval, and the other logic is basically the same.

/** ** @param fn {Function} Actual Function * @param delay {Number} execution interval, * * @return {Function} returns a "throttle" Function */ Function throttle(fn, Delay) {/ / record last time var last/var/timer timer / / the default interval is 250 ms delay | | (delay = 250) / / return function, Return function() {return function() {return function(); Var context = this var args = arguments var now = +new Date() If (last && now < last + delay) {clearTimeout(timer) Function () {last = now fn. Apply (context, args)} Else {last = now fn. Apply (context, args)}}}Copy the code

Usage scenarios

Throttle is used to limit the triggering frequency of resize and Scroll. Scroll, for example

Window. onscroll = _throttle(function(e) {console.log(1); }, 250).Copy the code

After using

Before using

conclusion

Debounce forces the function to execute once in a certain period of time, and throttle forces the function to execute at a fixed rate. Both can greatly improve the user experience when dealing with DOM events that are frequently triggered.