All files / sp-admin/util debounce.js

63.64% Statements 7/11
100% Branches 1/1
60% Functions 3/5
66.67% Lines 6/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25                3x 3x 3x   3x 3x               3x      
/**
 * Prevents a function from being called many times in a row
 * @param {Object} scope The scope to call inner with
 * @param {Function} inner The function to debounce (should return a Promise)
 * @param {Number} [ms=100] Number of milliseconds to wait before calling the function
 * @returns {Promise}
 */
export default function debounce (scope, inner, ms = 100) {
    let timer = null;
    let resolves = [];
    return function (...args) {
        // Run the function after a certain amount of time
        clearTimeout(timer);
        timer = setTimeout(() => {
            // Get the result of the inner function, then apply it to the resolve function of
            // each promise that has been created since the last time the inner function was run
            const result = inner.call(scope, ...args);
            resolves.forEach((r) => r(result));
            resolves = [];
        }, ms);
 
        return new Promise((resolve) => resolves.push(resolve));
    };
}