0

The code below simulates executing a live search (replaced with console output) via a debounce function.

The debounce function is called, but the passed liveSearch function is not. I'm guessing because debounce returns a function which isn't being executed.

How can I call liveSearch in such a way that it is actually debounced?

var MySearch = (function($) {
    var $search = $('.search'),
        searchDelay = 500,
        keysToIgnore = [8, 16, 17, 18, 27, 32, 37, 38, 39, 40, 91, 191, 220]; // space, esc, bkspc, ctrl, alt, cmd, arrows, /\

    function init() {
        $search.on('keyup', function(e) {
            if (keysToIgnore.indexOf(e.keyCode) == -1) {
                // FIXME: this isn't actually executing the passed liveSearch fn
                debounce(liveSearch, searchDelay);

                // This executes liveSearch, but doesnt debounce
                // debounce(liveSearch, searchDelay)();
            }
        });
    }

    function liveSearch() {
        console.log("searching:", $search.val());
    }

    // Remy's debounce func: 
    // https://remysharp.com/2010/07/21/throttling-function-calls
    function debounce(fn, delay) {
        console.log("debouncing for", delay);

        var timer = null;

        return function () {
            var context = this,
                args = arguments;

            clearTimeout(timer);

            timer = setTimeout(function () {
            fn.apply(context, args);
            }, delay);
        };
    }

    return {
        init: init
    };
}(jQuery));

jQuery(function() {
    MySearch.init();
});

http://codepen.io/bbodien/pen/BpWBXm?editors=0010

SpYk3HH
  • 22,272
  • 11
  • 70
  • 81
bbodien
  • 1,062
  • 2
  • 10
  • 20

1 Answers1

1

Each call of debounce creates its own closure with a timer variable. Hence the debounce function is designed to be called once and returns a function which should be called instead of liveSearch:

  function init() {
    var debouncedLiveSearch = debounce(liveSearch, searchDelay);

    $search.on('keyup', function(e) {
      if (keysToIgnore.indexOf(e.keyCode) == -1) {
        debouncedLiveSearch();
      }
    });
  }
Dark Falcon
  • 43,592
  • 5
  • 83
  • 98