Skip to content

Commit a8884d0

Browse files
authored
Merge pull request #40 from amrlabib/millisecond-accuracy
support millisecond accuracy and minor enhancement
2 parents c3e834f + 4946e43 commit a8884d0

File tree

4 files changed

+23
-5
lines changed

4 files changed

+23
-5
lines changed

app/App.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ function MyTimer({ expiryTimestamp }) {
4545
export default function App() {
4646
const time = new Date();
4747
time.setSeconds(time.getSeconds() + 600); // 10 minutes timer
48+
// time.setMilliseconds(time.getMilliseconds() + 6500); // 6.5 seconds timer
4849
return (
4950
<div>
5051
<MyTimer expiryTimestamp={time} />

src/useTimer.js

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,10 +56,25 @@ export default function useTimer(settings) {
5656
setExpiryTimestamp(newExpiryTimestamp);
5757
}
5858

59-
useEffect(() => {
60-
if (Validate.expiryTimestamp(expiryTimestamp)) {
59+
function handleExtraMilliSeconds(secondsValue, extraMilliSeconds) {
60+
setIsRunning(true);
61+
intervalRef.current = setTimeout(() => {
62+
intervalRef.current = undefined;
6163
setSeconds(Time.getSecondsFromExpiry(expiryTimestamp));
6264
start();
65+
}, extraMilliSeconds);
66+
}
67+
68+
useEffect(() => {
69+
if (Validate.expiryTimestamp(expiryTimestamp)) {
70+
const secondsValue = Time.getSecondsFromExpiry(expiryTimestamp);
71+
const extraMilliSeconds = Math.floor((secondsValue - Math.floor(secondsValue)) * 1000);
72+
setSeconds(secondsValue);
73+
if (extraMilliSeconds > 0) {
74+
handleExtraMilliSeconds(secondsValue, extraMilliSeconds);
75+
} else {
76+
start();
77+
}
6378
}
6479
return clearIntervalRef;
6580
}, [expiryTimestamp]);

src/utils/Time.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
export default class Time {
2-
static getTimeFromSeconds(totalSeconds) {
2+
static getTimeFromSeconds(secs) {
3+
const totalSeconds = Math.ceil(secs);
34
const days = Math.floor(totalSeconds / (60 * 60 * 24));
45
const hours = Math.floor((totalSeconds % (60 * 60 * 24)) / (60 * 60));
56
const minutes = Math.floor((totalSeconds % (60 * 60)) / 60);
@@ -17,7 +18,7 @@ export default class Time {
1718
const now = new Date().getTime();
1819
const milliSecondsDistance = expiry - now;
1920
if (milliSecondsDistance > 0) {
20-
return Math.floor(milliSecondsDistance / 1000);
21+
return milliSecondsDistance / 1000;
2122
}
2223
return 0;
2324
}

webpack.dev.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ module.exports = {
3333
devServer: {
3434
contentBase: path.join(__dirname, 'dev-dist'),
3535
compress: true,
36-
port: 9000
36+
port: 9000,
37+
disableHostCheck: true
3738
}
3839
}

0 commit comments

Comments
 (0)