Search code examples
jquerytwitter-bootstrapcaroufredseltypeerrorthrottling

jQuery Throttle - Debounce | callback.apply is not a function


I'm using Ben Alman's jQuery throttle - debounce script and I keep on running into an Uncaught TypeError when it is triggered.

It should also be said that I am using Twitter Bootstrap as a framework for responsive design, AND have a few synchronized CarouFredSels on the page as well.

The error I'm getting is this: Uncaught TypeError: callback.apply is not a function jquery.ba-throttle-debounce.js:149

I look at line 149 and this is the area of interest:

function wrapper() {
      var that = this,
        elapsed = +new Date() - last_exec,
        args = arguments;

      function exec() {
        last_exec = +new Date();
        callback.apply( that, args ); //LINE 149//
      };

      function clear() {
        timeout_id = undefined;
      };

      if ( debounce_mode && !timeout_id ) {
        exec();
      }

      timeout_id && clearTimeout( timeout_id );

      if ( debounce_mode === undefined && elapsed > delay ) {
        exec();

      } else if ( no_trailing !== true ) {
        timeout_id = setTimeout( debounce_mode ? clear : exec, debounce_mode === undefined ? delay - elapsed : delay );
      }
    };

I'm not really familiar with this script, since it was in place before I was asked to take over. The throttle script is triggered when the user clicks into a search field that toggles an "auto-complete" script to be implemented later on.

JFIDDLE


Solution

  • You have to swap the parameters.
    It's $.debounce(delay, callback) and not $.debounce(callback, delay)


    jQuery.debounce

    Debounce execution of a function. Debouncing, unlike throttling, guarantees that a function is only executed a single time, either at the very beginning of a series of calls, or at the very end. If you want to simply rate-limit execution of a function, see the jQuery.throttle method.

    Usage

    var debounced = jQuery.debounce( delay, [ at_begin, ] callback );
    
    jQuery('selector').bind( 'someevent', debounced );
    jQuery('selector').unbind( 'someevent', debounced );
    

    Arguments

    delay (Number)
    A zero-or-greater delay in milliseconds. For event callbacks, values around 100 or 250 (or even higher) are most useful.

    at_begin (Boolean)
    Optional, defaults to false. If at_begin is false or unspecified, callback will only be executed delay milliseconds after the last debounced-function call. If at_begin is true, callback will be executed only at the first debounced-function call. (After the throttled-function has not been called for delay milliseconds, the internal counter is reset)

    callback (Function)
    A function to be executed after delay milliseconds. The this context and all arguments are passed through, as-is, to callback when the debounced-function is executed.