Timerless Debounce in JavaScript

I wanted a debounce-like function today, but with a twist. Rather than waiting for a timeout, I wanted to wait until any current running instance of the function being debounced had finished.

Here’s a simple version of what I came up with:

function debounce2(func) {
    let isRunning = false;
    return function () {
        let context = this;
        let args = arguments;
        if (!isRunning) {
            isRunning = true;
            func.apply(context, args);
            isRunning = false;
        }
    };
};

As you can see, it’s just watching a boolean flag, that is set only while the function is running.

I needed support for Promises/Deferred, so my final version is this:

function debounce2(func) {
    let isRunning = false;
    let done = () => {
        isRunning = false;
    };
    return function () {
        let context = this;
        let args = arguments;
        if (!isRunning) {
            isRunning = true;
            let result = func.apply(context, args);
            if (result && result.hasOwnProperty("then")) {
                result.then(done, done);
            } else {
                isRunning = false;
            }
        }
    };
};

Hope this turns out to be useful. I’m not sure it’s technically a “debounce” or not, so if anyone has suggestions for a better name, please let me know in the comments.

Advertisements