New Year’s eve! Look at the mountains and rivers, clear and clear. May there be ravines in your heart to move forward.

Image stabilization

The event response function is executed after a period of time, and if it is called again within that period of time, the execution time is recalculated. When the function is not executed again within a predetermined time, doSomething is executed.

Application scenarios

  • Scroll Event The scroll is triggered
  • The search box enters the query
  • Form validation
  • Button submit event
  • Browser window playback, resize event
function debounce(func, wait, immediate){
    var timeout, result;   
    let decounced = function(){
        // Change the inner this pointer
        let context = this;
        // Get the event object, take the mouse event execution function argument
        let args = arguments;
        // Empty the timer every time the trigger event executes the function
        clearTimeout(timeout);
        if(immediate){
            letcallNow = ! timeout;// callNow is associated with timers
            // When the delay event arrives, the timer is cleared so that the func function can be re-executed
            timeout = setTimeout(() = > {
                timeout = null;
            }, wait);
            // Indicates immediate execution
            if(callNow) result = func.apply(context, args); // The execution event binding actually executes the context and parameters of the function

        }else {
            // Will not be executed immediately
            timeout = setTimeout(function(){
                result = func.apply(context, args);
            }, wait);
        }
        // Actually executes the return value of the function
        return result;
    }
    // Cancel the timer event
    decounced.cancel = function(){
        clearTimeout(timeout);
        timeout = null; // Prevent memory leaks
    }
    return decounced;
}

// The function to be buffered
function doSomeThing(e){
    console.log(this)   // Bind the event object BTN
    console.log(e)  // event Click on the event object
    
  	// Do something...
  
    return 'Desired result';   
}
/ / use
let doSome = debounce(doSomeThing, 5000);
// Bind click event, execute cancel timer event function
btn.onclick = function(){
    doSome.cancel();
}
Copy the code

The throttle

If events continue to fire, only one event will be executed every once in a while.

Application scenarios

  • DOM element drag function implementation
  • Shooting game
  • Calculate the distance the mouse moves
  • Listen for scroll events
function throttle(func, wait, options){
    let context, args, timeout;
    let old = 0;
    if(! options) options = {};return function(){
        context = this;
        args = arguments;

        let later = function(){
            old = new Date().valueOf();
            timeout = null;
            func.apply(context, args);
        }

        let now = new Date().valueOf();
        if(options.leading === false && !old){
            old = now;
        }
        if(now - old > wait){
            // Execute directly the first time
            if(timeout){
                clearTimeout(timeout);
                timeout = null;
            }
            func.apply(context, args);
            old = now;
        }else if(! timeout && options.trailing ! = =false) {// The last time will be executed
            timeout = setTimeout(later, wait); }}}function doSomeThing(e){
    console.log(this)   // Bind the event object BTN
    console.log(e)  // event Click on the event object
    container.innerHTML = count++;
    return 'Desired result';   
}

let doSome = throttle(doSomeThing, 1000, {
    leading: true.trailing: true
})
{trailing: false}} {trailing: false}} {trailing: false}} {trailing: false}} {trailing: false}} {trailing: false}

Copy the code