-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
91 lines (83 loc) · 2.95 KB
/
app.js
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
const typingText = document.querySelector(".typing-text p"),
inpField = document.querySelector(".wrapper .input-field"),
tryAgainBtn = document.querySelector(".content button"),
timeTag = document.querySelector(".time span b"),
mistakeTag = document.querySelector(".mistake span"),
wpmTag = document.querySelector(".wpm span"),
cpmTag = document.querySelector(".cpm span");
let timer,
maxTime = 60,
timeLeft = maxTime,
charIndex = mistakes = isTyping = 0;
function loadParagraph() {
const ranIndex = Math.floor(Math.random() * paragraphs.length);
typingText.innerHTML = "";
paragraphs[ranIndex].split("").forEach(char => {
let span = `<span>${char}</span>`
typingText.innerHTML += span;
});
typingText.querySelectorAll("span")[0].classList.add("active");
document.addEventListener("keydown", () => inpField.focus());
typingText.addEventListener("click", () => inpField.focus());
}
function initTyping() {
let characters = typingText.querySelectorAll("span");
let typedChar = inpField.value.split("")[charIndex];
if(charIndex < characters.length - 1 && timeLeft > 0) {
if(!isTyping) {
timer = setInterval(initTimer, 1000);
isTyping = true;
}
if(typedChar == null) {
if(charIndex > 0) {
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");
let wpm = Math.round(((charIndex - mistakes) / 5) / (maxTime - timeLeft) * 60);
wpm = wpm < 0 || !wpm || wpm === Infinity ? 0 : wpm;
wpmTag.innerText = wpm;
mistakeTag.innerText = mistakes;
cpmTag.innerText = charIndex - mistakes;
} else {
clearInterval(timer);
inpField.value = "";
}
}
function initTimer() {
if(timeLeft > 0) {
timeLeft--;
timeTag.innerText = timeLeft;
let wpm = Math.round(((charIndex - mistakes) / 5) / (maxTime - timeLeft) * 60);
wpmTag.innerText = wpm;
} else {
clearInterval(timer);
}
}
function resetGame() {
loadParagraph();
clearInterval(timer);
timeLeft = maxTime;
charIndex = mistakes = isTyping = 0;
inpField.value = "";
timeTag.innerText = timeLeft;
wpmTag.innerText = 0;
mistakeTag.innerText = 0;
cpmTag.innerText = 0;
}
loadParagraph();
inpField.addEventListener("input", initTyping);
tryAgainBtn.addEventListener("click", resetGame);