Converts human-readable time into milliseconds. No more multiplying by 60 in your head when setting up setTimeout, setInterval, or rate limiters.

The interval function accepts optional days, hours, minutes, and seconds and returns the total milliseconds.

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

Named constants read much better than magic numbers:

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 })