|
| 1 | +// Get the necessary elements |
| 2 | +const startButton = document.getElementById('start-btn'); |
| 3 | +const typedText = document.getElementById('typed-text'); |
| 4 | +const randomText = document.getElementById('random-text'); |
| 5 | +const wpmDisplay = document.getElementById('wpm'); |
| 6 | +const accuracyDisplay = document.getElementById('accuracy'); |
| 7 | + |
| 8 | +const sampleTexts = [ |
| 9 | + 'The quick brown fox jumps over the lazy dog.', |
| 10 | + 'JavaScript is a versatile programming language.', |
| 11 | + 'A journey of a thousand miles begins with a single step.', |
| 12 | + 'To be or not to be, that is the question.', |
| 13 | + 'Typing tests help improve typing speed and accuracy.', |
| 14 | +]; |
| 15 | + |
| 16 | +let startTime; |
| 17 | + |
| 18 | +// Start the typing test |
| 19 | +function startTest() { |
| 20 | + const randomIndex = Math.floor(Math.random() * sampleTexts.length); |
| 21 | + randomText.textContent = sampleTexts[randomIndex]; |
| 22 | + typedText.disabled = false; |
| 23 | + typedText.value = ''; |
| 24 | + typedText.focus(); |
| 25 | + startButton.disabled = true; |
| 26 | + startTime = new Date().getTime(); |
| 27 | + wpmDisplay.textContent = 'WPM: 0'; |
| 28 | + accuracyDisplay.textContent = 'Accuracy: 100%'; |
| 29 | +} |
| 30 | + |
| 31 | +// Calculate typing speed (WPM) and accuracy |
| 32 | +function calculateResults() { |
| 33 | + const typedValue = typedText.value; |
| 34 | + const randomTextValue = randomText.textContent; |
| 35 | + |
| 36 | + // Calculate WPM |
| 37 | + const timeTaken = (new Date().getTime() - startTime) / 1000; // in seconds |
| 38 | + const wordsTyped = typedValue.split(' ').length; |
| 39 | + const wpm = Math.round((wordsTyped / timeTaken) * 60); |
| 40 | + |
| 41 | + // Calculate accuracy |
| 42 | + let correctChars = 0; |
| 43 | + for (let i = 0; i < typedValue.length; i += 1) { |
| 44 | + if (typedValue[i] === randomTextValue[i]) { |
| 45 | + correctChars += 1; |
| 46 | + } |
| 47 | + } |
| 48 | + const accuracy = Math.round((correctChars / typedValue.length) * 100); |
| 49 | + |
| 50 | + wpmDisplay.textContent = `WPM: ${wpm}`; |
| 51 | + accuracyDisplay.textContent = `Accuracy: ${accuracy}%`; |
| 52 | + |
| 53 | + if (typedValue === randomTextValue) { |
| 54 | + setTimeout(() => { |
| 55 | + alert('Test Complete! Well done!'); |
| 56 | + startButton.disabled = false; |
| 57 | + }, 100); |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +// Event listeners |
| 62 | +startButton.addEventListener('click', startTest); |
| 63 | +typedText.addEventListener('input', calculateResults); |
0 commit comments