javascriptunderscore.jssettimeoutlodashdelayed-execution

Underscore debounce vs vanilla Javascript setTimeout


I understand that debounce in Undercore.js returns a function that will postpone its execution until the wait time is over.

My question is, is there an advantage of using debounce over the regular setTimeout function in vanilla Javascript? Don't they both work the same?


Solution

  • They are very different and used in completely different cases.

    1. _.debounce returns a function, setTimeout returns an id which you can use to cancel the timeOut.

    2. No matter how many times you call the function which is returned by _.debounce, it will run only once in the given time frame.

    var log_once = _.debounce(log, 5000);
    
    function log() {
      console.log('prints');
    }
    
    log_once();
    log_once();
    log_once();
    log_once();
    log_once();
    
    var id = setTimeout(function() {
      console.log('hello');
    }, 3000);
    clearTimeout(id);
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>