Report issue or request a feature · Make a pull request
- Written in TypeScript.
- Can be used with any JS library or framework.
- Uses (setInterval).
- Easy to use callback method.
- Return values include days, hours, minutes and seconds.
- Optional methods of alternative implementations.
$ npm install countdown-lib
import { Countdown, RemainingTimeType } from "countdown-lib";
// Any JavaScript supported date format can be used as long as it is passed as a Date object.
const countdown = new Countdown(new Date(2023, 0, 1, 0, 0, 0));
countdown.startCounter((remainder: RemainingTimeType, isComplete: boolean) => {
// isComplete will return false when all values are zero.
if (!isComplete) {
// Remainder should look something like this:
// { days: 45, hours: 5, minutes: 32, seconds: 12 }
console.log(remainder);
}
});
// These react imports may vary depending on your build tools.
import { react, FC, useState, useEffect } from "react";
import { Countdown, RemainingTimeType } from "countdown-lib";
export const CountdownExample: FC = () => {
const [remainingTime, setRemainingTime] = useState<RemainingTimeType>({
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
});
const [countdownComplete, setCountdownComplete] = useState<boolean>(false);
const countdown = new Countdown(new Date(2023, 0, 1, 0, 0, 0));
useEffect(() => {
if (isComplete) return;
countdown.startCounter(
(remainder: TimeRemainingType, isComplete: boolean) => {
setRemainingTime(remainder);
if (isComplete) {
setIsComplete(isComplete);
}
}
);
}, [remainingTime, setRemainingTime]);
return (
<div>{`${remainingTime.days} ${remainingTime.hours} ${remainingTime.minutes} ${remainingTime.seconds}`}</div>
);
};
Countdown()
// Breaking change as of version 2.1.0, constructor must be initialised with a Date object.
new Countdown(endDate: Date)
countdown.startCounter(callback)
// Starts a instance of setInterval that executes a callback every 1000ms with arguments
// for remaining time and a truthy value when countdown is complete.
countdown.startCounter(callback(remainder: TimeRemainingType, isComplete: boolean) => void): void;
countdown.stopCounter()
// Clears setInterval
countdown.stopCounter(): void
countdown.getRemainingTime()
// Optional method for retrieving remaining time outside of the .startCounter() callback.
countdown.getRemainingTime(): RemainingTimeType
countdown.addLeadingZero()
// Add leading zeroes to values < 10, ie. 01, 02, 03.
countdown.addLeadingZero(value: number): string
type RemainingTimeType = {
[key: string]: number;
days: number;
hours: number;
minutes: number;
seconds: number;
};