after()
after<
Args,Return>(func,n): (...args) =>Return|undefined
Creates a function that invokes func after it's called n or more times.
Type Parametersโ
Args: Args extends unknown[]โ
The argument types of the function.
Return: Returnโ
The return type of the function.
Parametersโ
func: (...args) => Returnโ
The function to restrict.
n: numberโ
The number of calls before func is invoked.
Returnsโ
The new restricted function. Returns undefined for the first n-1 calls.
Throwsโ
RangeError If n is negative or not an integer.
See Alsoโ
before - Inverse operation: invokes func at most n-1 times.
Sinceโ
2.0.0
Also known asโ
after (Lodash, es-toolkit) ยท โ (Remeda, Radashi, Ramda, Effect, Modern Dash, Antfu)
Exampleโ
let attempts = 0;
const saveData = after(() => {
attempts++;
console.log(`Data saved! Attempt #${attempts}`);
}, 3);
saveData(); // Nothing happens
saveData(); // Nothing happens
saveData(); // "Data saved! Attempt #1"
saveData(); // "Data saved! Attempt #2"
saveData(); // "Data saved! Attempt #3"
// Use case: Only start logging after initial setup calls
const logger = after((message: string) => {
console.log(`[LOG] ${message}`);
}, 2);
logger('Initializing...'); // Nothing (setup call)
logger('Loading config...'); // "[LOG] Loading config..."
logger('Ready!'); // "[LOG] Ready!"
How it works?โ
Creates a function that only invokes after being called n times.
The first n-1 calls return undefined โ starting from call n, the function executes normally.
Visual Timelineโ
Use Casesโ
Trigger after warmup period ๐โ
Execute only after a certain number of preliminary calls have occurred. Perfect for waiting until a system stabilizes or data accumulates.
// Only start calculating average after 5 data points
const updateAverage = after(5, (values) => {
const avg = values.reduce((a, b) => a + b, 0) / values.length;
displayAverage(avg);
});
sensor.on("reading", (value) => {
readings.push(value);
updateAverage(readings);
});
// First 4 readings: nothing happens
// 5th reading onward: average is displayed
Confirm after multiple signals ๐โ
Require multiple confirmations before executing a destructive action. Essential for safety mechanisms and preventing accidental triggers.
const confirmDelete = after(2, () => {
deleteAllData();
console.log("Data deleted after double confirmation");
});
// User must click "Delete" twice
deleteButton.on("click", confirmDelete);
Batch notifications after threshold ๐โ
Send a summary notification only after N events accumulate. Useful for reducing notification spam while still alerting users.
const notifyBatch = after(10, (errors) => {
sendAlert(`${errors.length} errors occurred in the last hour`);
});
errorStream.on("error", (err) => {
errorLog.push(err);
notifyBatch(errorLog);
});
// Alert sent only after 10+ errors