throttle






Usage scenarios
debounce
throttle






debounce
throttle
debounce
throttle



lodash
_.debounce()
_.throttle()


_.debounce(func, [wait=0], [options={}]) 


_.throttle(func, [wait=0], [options={}])Copy the code



1. debounce





_.debounce(func, [wait=0], [options={}])
Copy the code






Simple implementation


function debounce(fn, wait, options) {   
    wait = wait || 0;   
    var timerId;    


    function debounced() {   
        if (timerId) {   
            clearTimeout(timerId);

            timerId = null;   
        }   
        timerId = setTimeout(function() {   
            fn();     
      }, wait);
   }
    return debounced;
 }
Copy the code

debounce
debounced()









2. Throttle


_.throttle(func, [wait=0], [options={}])
Copy the code






deboucne
throttle






Simple implementation





function throttle(fn, wait, options) {   
    wait = wait || 0;   
    var timerId, lastTime = 0;    
    
    function throttled() {   
        var currentTime = new Date();   
        if (currentTime >= lastTime + wait) {   
            fn();   
            lastTime = currentTime;   
        } else {   
            if (timerId) {   
                clearTimeout(timerId);   
                timerId = null;   
            }   
            timerId = setTimeout(function() {   
                fn()   
            }, wait);   
       }   
    }    
    return throttled;  
}
Copy the code






A complete instance



Codepen. IO/TGCode/pen /…






conclusion





  • debounce: Consolidates events that trigger frequently into one execution.debounceThis works for events such as input, which responds to an Ajax request when the user enters, and multiple inputs only respond to a single callback method
  • throttle: Sets a threshold at which triggered events are combined into a single execution; And when the threshold is reached, an event must be executed.throttleThis function applies to resize events or mouse movement events, preventing the browser from frequently responding to events and severely reducing performance





  • Benalman.com/projects/jq…

  • Css-tricks.com/the-differe…