What does _.debounce do?

后端 未结 4 2020
轻奢々
轻奢々 2020-11-28 06:04

A project I\'ve been working on uses _.debounce().

The Underscore JS documentation for debounce reads as follows:

debounce <

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 06:27

    Description from the source code of underscore.js:

    Returns a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If 'immediate' is passed, trigger the function on the leading edge, instead of the trailing.

    Code it self:

    _.debounce = function(func, wait, immediate) {
      var timeout, result;
      return function() {
        var context = this, args = arguments;
        var later = function() {
          timeout = null;
          if (!immediate) result = func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) result = func.apply(context, args);
        return result;
      };
    };
    

提交回复
热议问题