Underscore debounce vs vanilla Javascript setTimeout

前端 未结 4 2076
有刺的猬
有刺的猬 2021-02-08 19:20

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 adva

4条回答
  •  余生分开走
    2021-02-08 19:43

    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);

提交回复
热议问题