Throttle Utility

The Throttle utility can be used to ensure that a function is only called once within a given delay, regardless of the number of times it is called. Useful for functions which are called rapidly, such as handlers for mouse events, scroll events, typing events, etc.

const Throttle = use('ElentraJS/Utility/Throttle');

function add(a, b) {
    return a + b;
};

let throttle = new Throttle();

// Call the add() method 5 times, each time with different arguments.
// Each call resets the delay.
for(let i = 0; i < 5; i++) {
    throttle.execute(add.bind(null, 1, i), 500).then(result => {
        // When add() is ultimately called, its return value is provided.
        console.log('Result: ', result);
    });
}

// add() is called once, 500ms after the most recent call, using the most recent set of arguments.
// Throttle.execute() returns a Promise which resolves with the return value of the add() call.
// Output: "Result: 5"

// Cancel execution
if(throttle.isRunning()) {
    throttle.break();
}

Last updated