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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { post } from '../../requests';
const Timer = () => {
const SPACE = 32;
const countdownInMills = 15000;
const [time, setTime] = useState("00:15:00");
const [running, setRunning] = useState(false);
const [timer, setTimer] = useState(0);
const [countdown, setCountdown] = useState(0);
const [countdownRunning, setCountdownRunning] = useState(false);
let startingTime;
const handleKeyDown = event => {
if (event.keyCode === SPACE && !running ) {
let timeGap = Date.now() - countdown;
if (!countdownRunning) {
setCountdown(Date.now());
setCountdownRunning(true);
timeGap = 0;
}
if (timeGap >= countdownInMills) {
setRunning(true);
setTime('00:00:00');
return;
}
setTime(() => {
const timeLeft = Math.floor((countdownInMills - timeGap) / 10);
let resultTime = "";
const minute = Math.floor(timeLeft / 6000);
if (minute < 10) resultTime += '0';
resultTime += minute + ':';
let second = Math.floor(timeLeft / 100);
if (second < 10) resultTime += '0';
if (second > 59) second %= 60;
resultTime += second + ':';
const mill = timeLeft % 100;
if (mill < 10) resultTime += '0';
resultTime += mill;
return resultTime;
})
}
}
const handleKeyUp = event => {
setCountdownRunning(false);
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);
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keyup", handleKeyUp);
window.removeEventListener("keydown", handleKeyDown);
};
})
return (
<Root>
<span>{time}</ span>
</Root>
);
}
const Root = styled.div`
background-color: skyblue;
padding: 8px;
display: inline-block;
font-size: 32px;
color: pink;
`;
export default Timer;
|