💾delay(f, s)
delay the execution of a function/method by s seconds.
JS ⟩ technique ⟩ decorator ⟩ 💾 delay(f, s)
replit:delay(f, s)
// 📁 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 };
replit:delay(f, s)
// 📁 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!"
Last updated