Skip to content

audit()

Eugene Lazutkin edited this page Feb 25, 2026 · 8 revisions

Description

The audit() function is a utility designed to limit the rate at which a specified function can be invoked. It helps in scenarios where excessive calls to a function may lead to performance issues or unintended behavior.

When the audited function is called, it starts a timer and arguments are stored. If the audited function is called again before the timer expires, new arguments replace the previous ones. Only after the timer expires will the function be executed with the last arguments passed to it.

It is similar to throttle(), but instead of executing the function on the first call and ignoring subsequent calls, it waits for the specified delay before executing with the last arguments.

Key features

  • Rate Limiting: Ensures that a function is executed only once within a specified time interval.
  • Flexible Parameters: Accepts any function and a delay in milliseconds.
  • Closure Support: Maintains the last arguments passed to the function for invocation after the delay.

Technical specifications

audit is available as a named and default export.

const auditedFn = audit(fn, ms);
  • Parameters:
    • fn: The function to be rate-limited. 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.

Usage Instructions

import audit from 'time-queues/audit.js';

// Example function to be audited
const log = message => console.log(message);

// Create a rate-limited version of the log function
const auditedLog = audit(log, 2000);

// Usage
auditedLog('First call'); // Ignored, but starts the timer
auditedLog('Second call'); // Ignored
setTimeout(() => auditedLog('Third call'), 1000); // Executes after 2000ms
setTimeout(() => auditedLog('Fourth call'), 3000); // Executes after 2000ms

Troubleshooting

  • Function Not Executing: Ensure that the delay (ms) is set correctly and that the function is not being called too frequently.
  • Arguments Not Passed: The last arguments are retained and passed after the delay; ensure that the function being audited can handle the arguments properly and passed values are not modified.

See Also

  • debounce() - Similar function for stabilizing input
  • sample() - Execute at regular intervals

Clone this wiki locally