blob: 1b7dec46510a221b23cf38fc2566d3cb7450b9cf (
plain)
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
|
import React, { useState, useEffect } from 'react';
import { Typography } from "@material-ui/core";
import {post} from '../../requests';
const Timer = () => {
const SPACE = 32
const [time, setTime] = useState("00:00:00")
const [running, setRunning] = useState(false);
const [timer, setTimer] = useState(0);
let startingTime;
const handleKeyUp = event => {
if (event.keyCode === SPACE){
if (!running) {
startingTime = Date.now();
setRunning(true);
setTimer(setInterval(() => setTime(() => {
const timeGap = Math.floor((Date.now() - startingTime) / 10);
let resultTime = "";
const minute = Math.floor(timeGap / 6000);
if (minute < 10) resultTime += '0';
resultTime += minute + ':';
let second = Math.floor(timeGap / 100);
if (second < 10) resultTime += '0';
if (second > 59) second %= 60
resultTime += second + ':';
const mill = timeGap % 100;
if (mill < 10) resultTime += '0';
resultTime += mill;
return resultTime;
}), 10))
} else {
clearInterval(timer);
setRunning(false);
startingTime = 0;
post('solutions/', {result: time});
return false;
}
}
}
useEffect(() => {
window.addEventListener("keyup", handleKeyUp);
return () => {
window.removeEventListener("keyup", handleKeyUp);
};
})
return (
<Typography variant="h2"> {time} </Typography>
);
}
export default Timer;
|