💾debounce(f, s)

suspends function calls until there's a specified period of inactivity, then invokes it.

JStechniquedecorator💾 debounce(f, s)

(decorator) suspends calls to f until there’s s seconds of inactivity (no further calls), then invokes the last function call (previous calls are ignored).

// 📁 debounce.js
// ⭐️ decorator: "debounce"
//   (suspends 'f' for 's' seconds)
function debounce(f, s) {

    // log
    console.log(`'${f.name}' has been debounced by ${s} seconds.`)

    // ⭐️ timer id
    let timer;

    // wrapper
    return function wrapper(...args) {
        
        // ⭐️ clear old timer (if it exits)        
        clearTimeout(timer);
        
        // ⭐️ set new timer (in s seconds)
        timer = setTimeout(
            () => f.apply(this, args),
            s * 1000
        );
    }
}

// export
module.exports = { debounce };

Last updated