Function debounce

The callback is executed n seconds after the event is triggered, and if it is triggered again within n seconds, the recalculation occurs

Look at an example:

Input without shake protection: <Input ID ="unDebounce"> <Input > Throttled <Input > function ajax(content) {console.log('ajax ' request' + content); } let inputa = document.getElementById('unDebounce') inputa.addEventListener('keyup', function (e) { ajax(e.target.value) })Copy the code

Take a look at the results: p1-jj.byteimg.com/tos-cn-i-t2… As you can see, as long as we press the keyboard, the Ajax request will be triggered, not only in terms of resources is a waste of behavior, but also in practical applications, the user will output a complete character, the request, let’s optimize

If the event is triggered again within n seconds, the time will be recalculated; Function debounce(fn) {let timeout = null // Create a token to store the timer return value return function () {clearTimeout(timeout) // SetTimeout = setTimeout(() => {// Then create a new setTimeout, This will make sure that if there are any more characters in the interval, Fn function fn.apply(this, arguments)} Function sayHi(n) {console.log(' debounce')} var inp = document.getelementById ('debounce') Inp. addEventListener('input', debounce(sayHi)) //Copy the code

Function throttle

Specifies that a function can fire only once per unit of time. If more than one function is fired in this unit of time, only one function will take effect

Function throttle(fn) {let canRun = true return function () {if (! CanRun) return // Check whether the flag is true at the beginning of the function, Return canRun = false if not true setTimeout(() => {// Put the execution of the external function in setTimeout fn.apply(this, Arguments) // Finally set the flag to true after setTimeout (key) the table is ready for the next loop. CanRun = true}, 10000)}} function sayHi(e) {console.log(' throttling !!!! ~~~') } // window.addEventListener('resize', throttle(sayHi)) document.getElementById('debounce').addEventListener('input', sayHi)Copy the code