0

Use case

  1. I have a list of person or group (like in FB messenger) (left pane)
  2. When I switch person, I load the message (API call).
  3. If I press down arrow quickly, then instead of making API call for each of the person, I want to load only the person who I pause and wait.
  4. Currently I am debouncing 300ms to achieve this.

    handleSwitchKeyEvent: function() {
        if (this.pendingLoad) {
            // Still pending continue to debounce
            clearTimeout(this.pendingLoad);
            fn = this.loadContent;
        } else {
            // No longer pending - So load data immediately
            this.loadContent();
        }
    
        // Delay the load
        this.pendingLoad = setTimeout(function () {
            clearTimeout(this.pendingLoad);
            this.pendingLoad = 0;
            fn && fn.call(this);
        }, 300);
    }
    

Problem

  1. When I am at Message1 - M1 details are loaded
  2. When I press key fast - M2 will load and then de-bounce will happen for the next message)

I want to avoid this M2 load. I am not sure whether that is even possible to mix debouce and non-debounce in the same flow

Prabhakar Kasi
  • 531
  • 4
  • 18
  • Could you just store the key event value in an object or something and then have your debounce code first check the value of that object before debouncing? Like, it the previous key value is the same as the current event value, it then debounces, but otherwise it doesnt. – Pytth Nov 18 '15 at 21:50

1 Answers1

1

Instead of "debounce" you're probably looking for something that kicks off a timeout and waits a set duration before calling the function with the last arguments passed in. Here's a quick'n'dirty buffering function (untested):

function buffer( fn, duration ) {
    // Store a timeout id and last args called with
    var buffer;
    var lastArgs;
    return function( ) {
        // The last args will be used
        lastArgs = arguments;
        // If buffer hasn't started, kick it off
        if (!buffer) {
            buffer = setTimeout(function() {
                // After duration, call the function with args
                // Reset buffer
                fn.apply(null, lastArgs);
                buffer = null;
            }, duration);
        }
    }
}

Edit: Forgot to clear buffer variable

TbWill4321
  • 8,626
  • 3
  • 27
  • 25