Here is a simple utility function that creates a delay between function calls in JavaScript or TypeScript. This can be useful for scenarios where you need to throttle or debounce function calls, or create a delay between API requests.
The interval
function takes an object with optional days
, hours
, minutes
, and seconds
properties, and returns the total number of milliseconds.
This function is useful when you need to create a delay between function calls, for example, to throttle user input or to limit the rate of API requests.
interface IntervalOptions {
hours?: number
minutes?: number
seconds?: number
days?: number
}
function interval({
hours = 0,
minutes = 0,
seconds = 0,
days = 0,
}: IntervalOptions): number {
return (((days * 24 + hours) * 60 + minutes) * 60 + seconds) * 1000
}
Usage example
Here is an example of how you can use the interval
function to create delays between function calls:
import { interval } from './milliseconds-interval-helper'
const FIVE_SECONDS = interval({ seconds: 5 })
const ONE_MINUTE = interval({ minutes: 1 })
const ONE_HOUR = interval({ hours: 1 })
const ONE_DAY = interval({ days: 1 })