๐Ÿ’พdebounce(f, s)

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

JS โŸฉ technique โŸฉ decorator โŸฉ ๐Ÿ’พ debounce(f, s)

// ๐Ÿ“ 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

Was this helpful?