delay the execution of a function/method by s seconds.
Last updated 2 years ago
Was this helpful?
โฉ โฉ โฉ delay(f, s)
(decorator) delay the execution of a function/method by s seconds.
replit๏ผ
// ๐ 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 };
// ๐ index.js const { delay } = require('./delay.js'); // function function f(x) { console.log(` โข ${x}`); } // object method const joe = { name: 'Joe', say(anything) { console.log(` โข ${this.name}: "${anything}"`) }, } // โ delaying method delay(joe.say, 3)('long time no see!'); // โ `this` === undefined (in module context) // โญ๏ธ "delay" and "reassign" method joe.say = delay(joe.say, 4); // โ `this` is still unbound joe.say('nice to meet you!'); // โญ๏ธ `this` === `joe` (at call site) // โญ๏ธ delaying f function delay(f, 1)('hello'); delay(f, 2)('world'); // log // ------------------------------------ // 1: f('hello') ... // โข hello // 2: f('world') ... // โข world // 3: say('long time no see!') ... // โข undefined: "long time no see!" <---- `this` === undefinedโ // 4: say('nice to meet you!') ... // โข Joe: "nice to meet you!"
YDKJS: Scope & Closures (v.2) โฉ Ch. 6 (by IIFE, ie. closure)
decorator
JS.info โฉ โญ๏ธ
(by parameter)
Wictionary โฉ