Anti-shake, which can be used to prevent users from clicking login and sending SMS buttons for many times in a short period of time, sending multiple requests, or adjusting the browser window size, resize times are too frequent, resulting in too much calculation. And that’s something that needs to be optimized in the project,

function debounce(fn, delay) {
            let timer = null
            return function () {
                let context = this
                let args = arguments
                clearTimeout(timer)
                timer = setTimeout(function () {
                    fn.call(context, args) 
                },delay)
            }
        }
Copy the code

Throttling, which can only be triggered once in a short period of time, is used to optimize functions that are used frequently

function throttle(fn, delay) { let timer = null return function () { let context = this let args = arguments if (! timer) { timer = setTimeout(function () { fn.call(context, args) timer = null }, delay) } } }Copy the code
function throttle(fn, delay) { let prev = 0 return function () { let now = new Date(); if (now - prev > delay) { fn() prev = now; }}}Copy the code