Aller au contenu principal

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