Skip to content

Commit

Permalink
Merge pull request #40 from amrlabib/millisecond-accuracy
Browse files Browse the repository at this point in the history
support millisecond accuracy and minor enhancement
  • Loading branch information
amrlabib authored Nov 30, 2020
2 parents c3e834f + 4946e43 commit a8884d0
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
1 change: 1 addition & 0 deletions app/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ function MyTimer({ expiryTimestamp }) {
export default function App() {
const time = new Date();
time.setSeconds(time.getSeconds() + 600); // 10 minutes timer
// time.setMilliseconds(time.getMilliseconds() + 6500); // 6.5 seconds timer
return (
<div>
<MyTimer expiryTimestamp={time} />
Expand Down
19 changes: 17 additions & 2 deletions src/useTimer.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,25 @@ export default function useTimer(settings) {
setExpiryTimestamp(newExpiryTimestamp);
}

useEffect(() => {
if (Validate.expiryTimestamp(expiryTimestamp)) {
function handleExtraMilliSeconds(secondsValue, extraMilliSeconds) {
setIsRunning(true);
intervalRef.current = setTimeout(() => {
intervalRef.current = undefined;
setSeconds(Time.getSecondsFromExpiry(expiryTimestamp));
start();
}, extraMilliSeconds);
}

useEffect(() => {
if (Validate.expiryTimestamp(expiryTimestamp)) {
const secondsValue = Time.getSecondsFromExpiry(expiryTimestamp);
const extraMilliSeconds = Math.floor((secondsValue - Math.floor(secondsValue)) * 1000);
setSeconds(secondsValue);
if (extraMilliSeconds > 0) {
handleExtraMilliSeconds(secondsValue, extraMilliSeconds);
} else {
start();
}
}
return clearIntervalRef;
}, [expiryTimestamp]);
Expand Down
5 changes: 3 additions & 2 deletions src/utils/Time.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export default class Time {
static getTimeFromSeconds(totalSeconds) {
static getTimeFromSeconds(secs) {
const totalSeconds = Math.ceil(secs);
const days = Math.floor(totalSeconds / (60 * 60 * 24));
const hours = Math.floor((totalSeconds % (60 * 60 * 24)) / (60 * 60));
const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
Expand All @@ -17,7 +18,7 @@ export default class Time {
const now = new Date().getTime();
const milliSecondsDistance = expiry - now;
if (milliSecondsDistance > 0) {
return Math.floor(milliSecondsDistance / 1000);
return milliSecondsDistance / 1000;
}
return 0;
}
Expand Down
3 changes: 2 additions & 1 deletion webpack.dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ module.exports = {
devServer: {
contentBase: path.join(__dirname, 'dev-dist'),
compress: true,
port: 9000
port: 9000,
disableHostCheck: true
}
}

0 comments on commit a8884d0

Please sign in to comment.