💾delay(f, s)

delay the execution of a function/method by s seconds.

(decorator) delay the execution of a function/method by s seconds.

// 📁 delay.js
const { log } = console;

// ⭐️ decorator: "delay"
//    (delay execution by s seconds)
function delay(f, s) {

    // wrapper
    return function wrapper(...args) {

        // delay execution
        setTimeout(

            // ❗ msut use "arrow function" here. 
            // ❗ `this` context is taken from the `wrapper`.
            () => {
                
                // add single-quotes ('') to string arguments
                let arglist = args
                    .map(arg => typeof arg === 'string' ? `'${arg}'` : arg)
                    .join(' ,');
                
                // log execution time, function name, arguments
                log(`${s}: ${f.name}(${arglist}) ...`);

                // ⭐️ forward function call to `f`
                f.apply(this, args);    // ❗ `this` context taken from `wrapper`
            },

            // execute after s seconds
            s * 1000
        );
    }
}

// export
module.exports = { delay };

Last updated