Anti – shake throttling usually used in the front end of the project, today to give a preliminary introduction.

1. What is anti-shake and throttling

  • Image stabilization

    Image stabilization methods and behavior is to be performed, will open a countdown in the beginning, if in the countdown time execution methods and behavior, so the countdown to empty, to start the countdown, countdown to the global only one, at the end of the countdown, have you want to the content of the execution method.

    Anti-tremble is often used to monitor users’ resize, scroll and other operations on the browser. It is impossible for us to execute our callback function for users’ frequent operations (with very short intervals), which will destroy the performance of the browser greatly. In order to avoid this problem, I wrote a basic anti-scroll callback function here.

The demo code

// The buffeting function
function debounce(func, wait) {
    if(typeoffunc ! = ='function') {
        throw new TypeError('need a function')}let timeId = null
    return function() {
        console.log('Rolled, rolled, rolled.')
        if(timeId) clearTimeout(timeId)
        timeId = setTimeout(() = > {
            func.apply(this.arguments) }, wait); }}//scrollhandler
function scrollHandler(e) {
    console.log("Trigger scroll", e)
}
document.addEventListener('scroll', debounce(scrollHandler, 2000))
Copy the code

The results

  • The throttle

    Throttling means that method content can only be executed once, no matter how many times the user executes methods and behaviors over a specified interval of time.

    Throttling is often used when the user clicks a button or enters an input box to perform time-consuming or asynchronous code. Frequent user clicks or input will cause multiple requests or time-consuming, resulting in high performance overhead.

    The demo code

/ / throttling
function throttle(func, gapTime) {
    if(typeoffunc ! = ='function') {
        throw new TypeError('need a function')}let lastTime = 0
    console.log("Crazy click")
    return function() {
        const time = +new Date(a)if(time - lastTime > gapTime) {
            func.apply(this.arguments)
            lastTime = time
        }
    }
}

document.querySelector('#btn').addEventListener('click', throttle(clickHandler, 2000))
Copy the code

The results

  • Why do we use closures here?

If you return an anonymous function, it will not be destroyed if the anonymous function continues to reference the variable, creating a closure, and the variable will remain in memory. Therefore, it can determine whether the countdown setTimeout exists. If it exists, it will be cleared; if it does not, it will be re-created.