1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
|
import React, { useState, useEffect } from 'react';
import { Paper, Typography } from '@material-ui/core';
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles(theme => ({
root: {
textAlign: 'center',
padding: theme.spacing(5),
background: theme.palette.primary.main,
},
}));
const Timer = ({ registerResult }) => {
const classes = useStyles();
const SPACE = 32;
const maxCountdown = 15000;
const [time, setTime] = useState('00:00:00');
const [isRunning, setIsRunning] = useState(false);
const [timer, setTimer] = useState(0);
const [isCountdown, setIsCountdown] = useState(false);
let startingTime;
const handleKeyPress = event => {
event.preventDefault();
if (event.keyCode === SPACE && !isRunning ) {
if (!isCountdown) {
startingTime = Date.now();
setIsCountdown(true);
setTimer(setInterval(() => setTime(() => {
const timeDiff = maxCountdown - (Date.now() - startingTime);
if (timeDiff < 0) {
setIsRunning(true);
setTime('00:00:00');
clearInterval(timer);
}
return convertTimeToString(timeDiff);
}), 10));
}
}
};
const handleKeyUp = event => {
if (event.keyCode === SPACE) {
clearInterval(timer);
if (!isRunning) {
startingTime = Date.now();
setIsRunning(true);
setTimer(setInterval(() => setTime(convertTimeToString((Date.now() - startingTime))), 10));
} else {
clearInterval(timer);
setIsRunning(false);
setIsCountdown(false);
startingTime = 0;
registerResult(time);
return false;
}
}
};
useEffect(() => {
window.addEventListener('keyup', handleKeyUp);
window.addEventListener('keypress', handleKeyPress);
return () => {
window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('keypress', handleKeyPress);
};
});
return (
<Paper elevation={3} className={classes.root}>
<Typography variant="h1"> {time} </Typography>
</Paper>
);
};
const convertTimeToString = timeDiff => {
let resultTime = '';
const minute = Math.floor(timeDiff / 60000);
if (minute < 10) resultTime += '0';
resultTime += minute + ':';
let second = Math.floor(timeDiff / 1000);
if (second < 10) resultTime += '0';
if (second > 59) second %= 60;
resultTime += second + ':';
const mill = Math.floor((timeDiff % 1000) / 10);
if (mill < 10) resultTime += '0';
resultTime += mill;
return resultTime;
};
export default Timer;
|