blob: d0f8ff107fda772f0acd3cf16d196e7224a52f6b (
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
67
68
69
70
71
72
73
74
75
|
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
const Timer = () => {
const [minute, setMinute] = useState(0);
const [second, setSecond] = useState(0);
const [mill, setMill] = useState(0);
const [time, setTime] = useState("00:00:00")
const [stopwatchStart, setStopwatchStart] = useState(false);
const [stopwatchTime, setStopwatchTime] = useState(0);
const handleKeyDown = event => {
if (event.keyCode === 32){
if (!stopwatchStart) {
setStopwatchTime(Date.now());
setStopwatchStart(true);
}
const timeGap = Date.now() - stopwatchTime;
setMill(Math.floor((timeGap % 1000) / 10));
setSecond(Math.floor(timeGap / 1000));
setMinute(Math.floor(timeGap / 60000));
setTime(() => {
let resultTime = "";
if (minute < 10) resultTime += '0';
resultTime += minute + ':';
if (second < 10) resultTime += '0';
resultTime += second + ':';
if (mill < 10) resultTime += '0';
resultTime += mill;
return resultTime;
});
}
}
const handleKeyUp = event => {
if (event.keyCode === 32) {
setTime("00:00:00");
setMill(0);
setSecond(0);
setMinute(0);
setStopwatchStart(false);
setStopwatchTime(0);
}
}
useEffect(() => {
window.addEventListener("keydown", handleKeyDown);
window.addEventListener("keyup", handleKeyUp);
return () => {
window.removeEventListener("keydown", handleKeyDown);
window.removeEventListener("keyup", handleKeyUp);
};
})
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;
|