Lodash Debounce not debouncing

前端 未结 2 1898
旧时难觅i
旧时难觅i 2020-12-16 11:11

I\'m trying to debounce a function using Lodash, and while it\'s invoking the function, it doesn\'t seem to debounce it at all. My issue doesn\'t seem to be the same mistake

相关标签:
2条回答
  • 2020-12-16 11:38

    _.debounce creates a function that debounces the function that's passed into it. What your s.search function is doing is calling _.debounce all over again every time s.search is called. This creates a whole new function every time, so there's nothing to debounce.

    So the solution is to remove the arrow and the extra pair of parentheses, and make sure that s._makeSearchRequest is defined before you access it:

    s._makeSearchRequest = -> console.log("making search request")
    
    s.search = _.debounce( s._makeSearchRequest, 1000 )
    

    Example (using JavaScript):

    var s;
    
    s = {};
    
    s._makeSearchRequest = function(q) {
      return console.log("making search request: " + q);
    };
    
    s.search = _.debounce(s._makeSearchRequest, 1000);
    
    // call s.search three times in a row
    s.search(1);
    s.search(2);
    s.search(3);
    
    // call s.search after 500 ms
    setTimeout(s.search, 500, 4);
    
    // call s.search after 3 seconds
    setTimeout(s.search, 3000, 5);
    
    // timer to show passage of time
    var i = 0;
    var t = setInterval(function () {
        i += 1;
        console.log(i + " seconds elapsed");
        if (i > 5) { clearInterval(t); }
    }, 1000);
    <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.min.js"></script>

    0 讨论(0)
  • 2020-12-16 11:54

    Try this:

    s._makeSearchRequest = function() {
        console.log("making search request");
    }
    
    s.search = _.debounce( s._makeSearchRequest, 1000 );
    

    POC: http://jsfiddle.net/bvaughn/3saj6znk/

    0 讨论(0)
提交回复
热议问题