클릭속도 테스트
녹색 화면이 나왔을 때 클릭 속도를 측정하는 프로그램을 작성하시오.
개인 풀이
다이어그램
알고리즘
const $screen = document.querySelector(".screen");
const $timeDiff = document.querySelector(".timeDiff");
const $log = document.querySelector(".log");
const recordArray = [];
let timeout;
let startTime, endTime, timeDiff;
let flag = true;
const handleScreenClick = (e) => {
if (flag === false) return;
if ($screen.style.backgroundColor === "blue") {
$screen.style.backgroundColor = "tomato";
$screen.textContent = "대기";
timeout = setTimeout(() => {
$screen.style.backgroundColor = "green";
$screen.textContent = "클릭하세요!";
// 타이머 시작
startTime = new Date().getTime() / 1000;
}, Math.floor(Math.random() * 2000) + 2000);
} else if ($screen.style.backgroundColor === "tomato") {
$screen.textContent = `너무 빨랐습니다!`;
clearTimeout(timeout);
setTimeout(init, 2000);
} else if ($screen.style.backgroundColor === "green") {
// 타이머 종료
flag = false;
endTime = new Date().getTime() / 1000;
timeDiff =
Math.round((endTime - startTime + Number.EPSILON) * 10000) / 10000;
$screen.innerHTML = `성공!<br>${timeDiff}초 만에 성공했습니다.`;
recordArray.push(timeDiff);
let averageSpeed =
recordArray.reduce((accm, curr) => accm + curr) / recordArray.length;
$log.textContent = `평균 속도: ${averageSpeed}초`;
setTimeout(init, 3000);
}
};
const init = () => {
$screen.style.backgroundColor = "blue";
$screen.addEventListener("click", handleScreenClick);
$screen.textContent = "시작";
startTime = 0;
endTime = 0;
flag = true;
};
init();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
.screen {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
width: 400px;
height: 300px;
font-size: 20px;
color: white;
}
</style>
</head>
<body>
<div class="screen"></div>
<span class="timeDiff"></span>
<div class="log"></div>
<script src="index.js"></script>
</body>
</html>