-
-
Notifications
You must be signed in to change notification settings - Fork 0
sample()
Eugene Lazutkin edited this page Feb 25, 2026
·
7 revisions
The sample() function is a utility that allows for the execution of a given function (fn) after a specified delay (ms). It ensures that the function is only called once during a specified time interval, regardless of how many times it is triggered. This is particularly useful for scenarios like throttling events.
The function retains the last arguments passed to it within the specified time interval and calls the function with those arguments at the end of the interval. It is similar to audit(), but instead of starting a timer on the first call, it runs intervals constantly. If no calls were made during the interval, the function is not called.
- Throttling: Prevents the function from being called multiple times in rapid succession.
- Lightweight: Minimal code footprint, making it easy to integrate into various projects.
sample() is available as a named and default export.
const sampledFn = sample(fn, ms);-
Parameters:
-
fn: The function to be sampled. It can have any number of arguments. Its return value will be ignored. -
ms: The time interval (in milliseconds) within which subsequent calls to the function will be ignored.
-
- Return Value: Returns a new function that can be called with any arguments.
- TypeScript Support: Includes TypeScript self-types for better integration with TypeScript projects.
import sample from 'time-queues/sample.js';
const log = () => console.log('Function executed!');
// Call the sample function with a 1000ms delay
const sampledLog = sample(log, 1000);
// Trigger the sampled function
sampledLog(); // Will execute log after 1000ms delay
sampledLog(); // Subsequent calls within 1000ms will be ignored- Function Not Executing: Ensure that the delay (ms) is set correctly and that the function is being called within the expected timeframe.
- Arguments Not Passed: The last arguments are retained and passed after the delay; ensure that the function being sampled can handle the arguments properly and passed values are not modified.
- throttle() - Rate limiting function
- audit() - Execute after delay
- Scheduler - Time-based scheduling