티스토리 뷰
const typingText = document.querySelector(".typing__text p");
const inputField = document.querySelector(".input__field");
const typingMistake = document.querySelector(".mistake span");
const typingTime = document.querySelector(".time span b");
const typingWpm = document.querySelector(".wpm span"); //1분동안 친 단어
const typingCpm = document.querySelector(".cpm span"); //1분동안 친 글자수
const typingAgain = document.querySelector(".again");
let charIndex = 0;
let mistakes = 0;
let timer;
let maxTime = 60;
let timeLeft = maxTime;
let isTyping = 0;
function randomParagraph(){
let randIndex = Math.floor(Math.random()*paragraphs.length);
typingText.innerHTML = "";
// console.log(paragraphs[randIndex].split(""));
paragraphs[randIndex].split("").forEach(span => {
let spanTag = `<span>${span}</span>`;
typingText.innerHTML += spanTag;
});
//인풋박스로 포커싱 되게하기
document.addEventListener("keydown", ()=> inputField.focus());
typingText.addEventListener("click", ()=> inputField.focus());
}
function initTyping(){
const characters = typingText.querySelectorAll("span");
let typedChar = inputField.value.split("")[charIndex];
if(charIndex < characters.length -1 && timeLeft > 0){
if(!isTyping){
timer = setInterval(initTimer, 1000);
isTyping = true;
}
if(typedChar == null){
charIndex--;
if(characters[charIndex].classList.contains("incorrect")){
mistakes--;
}
characters[charIndex].classList.remove("correct", "incorrect");
} else {
if(characters[charIndex].innerText === typedChar){
characters[charIndex].classList.add("correct");
} else {
mistakes++;
characters[charIndex].classList.add("incorrect");
}
charIndex++;
}
characters.forEach(span => span.classList.remove("active"));
characters[charIndex].classList.add("active");
typingMistake.innerText = mistakes;
//전체 글자 수 : charIndex
let wpm = Math.round((((charIndex - mistakes)/5) / (maxTime - timeLeft)) * 60);
let cpm = Math.round((((charIndex - mistakes)) / (maxTime - timeLeft)) * 60);
wpm = wpm < 0 || !wpm || wpm == Infinity ? 0 : wpm;
cpm = cpm < 0 || !cpm || cpm == Infinity ? 0 : cpm;
typingWpm.innerText = wpm;
typingCpm.innerText = cpm;
} else {
clearInterval(timer);
inputField.value = "";
}
// console.log(typedChar);
function initTimer(){
if(timeLeft > 0){
timeLeft--;
typingTime.innerText = timeLeft;
} else {
clearInterval(timer);
}
}
}
//트라이 어게인 함수
function resetGame(){
clearInterval(timer);
inputField.value = "";
timeLeft = maxTime;
isTyping = charIndex = mistakes = 0;
typingWpm.innerText = 0;
typingCpm.innerText = 0;
typingMistake.innerText = mistakes;
randomParagraph();
}
randomParagraph();
inputField.addEventListener("input", initTyping);
typingAgain.addEventListener("click", resetGame);
타자연습에 들어가는 글은 배열 형식에 맞게 데이터화 시켜서 불러옵니다.
'Javascript' 카테고리의 다른 글
Json 이란? (0) | 2022.04.11 |
---|---|
FTP 란? (0) | 2022.04.11 |
javascript 뮤직 플레이어 만들기 (0) | 2022.04.08 |
jQuery 란? (0) | 2022.04.08 |
mouseover, mouseenter, mouseout, mouseleave (이벤트 버블링) (0) | 2022.02.23 |
댓글
© 2018 webstoryboy