A comprehensive, flexible, and efficient duration manipulation utility for JavaScript.
Inspired by the Dart programming language's Duration class, duration-util
offers a similar experience for JavaScript developers, providing a rich set of functionalities to handle time durations with ease.
npm install duration-util
import { Duration, setDurationTimeout, setDurationInterval, sleep } from "duration-util";
const duration = new Duration({ hours: 1, minutes: 30 });
console.log(duration.toMinutes()); //=> 90
// Using utility functions
setDurationTimeout(() => {
console.log("Timeout after 2 minutes");
}, Duration.fromMinutes(2));
setDurationInterval(() => {
console.log("Interval every 10 seconds");
}, Duration.fromSeconds(10));
(async () => {
await sleep(Duration.fromSeconds(5));
console.log("Slept for 5 seconds");
})();
options
:DurationOptions
|number
- Duration options or milliseconds.- Returns:
Duration
instance.
- Static methods to create
Duration
from different time units. milliseconds
,seconds
,minutes
, etc.:number
- Returns:
Duration
instance.
- Conversion methods to get the duration in different time units.
- Returns:
number
- Arithmetic methods to manipulate durations.
other
:Duration
,factor
,divisor
:number
- Returns:
Duration
instance.
- Getter methods for different time units.
- Returns:
number
- Formats the duration according to a template string.
template
:string
- Returns:
string
- Returns a string representation of the duration.
- Returns:
string
callback
:() => void
- Function to execute after timeout.duration
:Duration
- Duration to wait before executing the callback.
callback
:() => void
- Function to execute at each interval.duration
:Duration
- Interval duration.
duration
:Duration
- Duration to sleep.- Returns:
Promise<void>