// import import React, { useEffect, useState } from 'react'; /** * component timer * * @param props * @returns */ const ComponentTimer = (props = {}) => { // state const [updated, setUpdated] = useState(null); // start const { start } = props; // start date const startDate = new Date(start); // time in ms const time = new Date(props.end || new Date()).getTime() - startDate.getTime(); // use effect useEffect(() => { // check end if (props.end) return; // set updated const interval = setInterval(() => { setUpdated(new Date().getTime()); }, 100); // return clear interval return () => clearInterval(interval); }, [props.end]); // humanize time const humanize = () => { // hours, minutes, seconds, optionally const hours = Math.floor(time / 3600000); const minutes = Math.floor((time % 3600000) / 60000); const seconds = Math.floor((time % 60000) / 1000); // return return `${hours ? `${hours}h ` : ''}${minutes ? `${minutes}m ` : ''}${seconds ? `${seconds}s` : ''}`; }; // return time return ( {humanize()} ) } /** * export component */ export default ComponentTimer;