본문 바로가기

FE/REACT

[리액트]js선수 지식 - 8장 Date사용하기 -반응속도 테스트

반응속도가 얼마나 빠른지 확인하는 테스트이고, 시간을 측정해야 하므로 date객체를 사용한다.

 

▶html 화면 구성& 간단한 script

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>반응속도</title>
<style>
  #screen {
    width: 300px;
    height: 200px;
    text-align: center;
    user-select: none;
  }
  #screen.waiting {
    background-color: aqua;
  }
  #screen.ready {
    background-color: red;
    color: white;
  }
  #screen.now {
    background-color: greenyellow;
  }
</style>
</head>

<body>

<script>
  const $screen = document.querySelector('#screen');
  const $result = document.querySelector('#result');
</script>
</body>
</html>

▶이벤트 리스너를 달아 화면별로 다르게 동작하도록 구현 

waiting클래스: 대기화면, 

ready클래스: 준비화면

now클래스: 클릭화면

 

▶평균 반응 속도 구하기 

테스트를 반복적으로 수행해서 평균 반응 속도를 구해야 하고, 기존의 반응속도를 모두 기록하기 위해서 records라는 배열을 만들어 준다.

 

 

이번 파트는 설명하기 애매해서, 코드로 대신한답,,!

전체 코드)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>반응속도</title>
<style>
    #screen {
    width: 300px;
    height: 200px;
    text-align: center;
    user-select: none;
    }
    #screen.waiting {
    background-color: aqua;
    }
    #screen.ready {
    background-color: red;
    color: white;
    }
    #screen.now {
    background-color: greenyellow;
    }
</style>
</head>

<body>
<div id="screen" class="waiting">클릭해서 시작하세요</div>
<div id="result"></div>
<script>
    const $screen = document.querySelector('#screen');
    const $result = document.querySelector('#result');
    
    let startTime;
    let endTime;
    //records배열
    const records = [];

    let timeoutId;
    $screen.addEventListener('click',(event)=>{
    if (event.target.classList.contains('waiting')){ // 파랑
        $screen.classList.remove('waiting');
        $screen.classList.add('ready');
        $screen.textContent = '초록색이 되면 클릭하세요';
        timeoutId = setTimeout(function () {
            startTime = new Date();
            $screen.classList.remove('ready');
            $screen.classList.add('now');
            $screen.textContent = '클릭하세요!';
      }, Math.floor(Math.random() * 1000) + 2000); // 2초에서 3초 사이 2000~3000 사이 수
    }
    else if (event.target.classList.contains('ready'))
    { // 빨강
        clearTimeout(timeoutId);
        $screen.classList.remove('ready');
        $screen.classList.add('waiting');
        $screen.textContent = '너무 성급하시군요!';
    }else if (event.target.classList.contains('now')) 
    { // 초록
        endTime = new Date();
        const current = endTime - startTime;
        records.push(current);
        const average = records.reduce((a, c) => a + c) / records.length;
        $result.textContent = `현재 ${current}ms, 평균: ${average}ms`;
        startTime = null;
        endTime = null;
        $screen.classList.remove('now');
        $screen.classList.add('waiting');
        $screen.textContent = '클릭해서 시작하세요';
    }
    });
</script>
</body>
</html>

 

 

 

 

 

 

결과)