Skip to content

Commit

Permalink
Add playing flag and start timer when key is pressed
Browse files Browse the repository at this point in the history
  • Loading branch information
JuanCarlosAcostaPeraba committed Apr 3, 2024
1 parent 2d74604 commit 6406ef8
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions 03-midu-typing-game/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ <h3 id="results-accuracy"></h3>

let words = []
let currentTime = INITIAL_TIME
let playing

initGame()
initEvents()
Expand All @@ -186,6 +187,8 @@ <h3 id="results-accuracy"></h3>
$results.style.display = 'none'
$input.value = ''

playing = false

words = INITIAL_WORDS.toSorted(
() => Math.random() - 0.5
).slice(0, 50)
Expand All @@ -208,25 +211,28 @@ <h3 id="results-accuracy"></h3>
const $firstWord = $paragraph.querySelector('word')
$firstWord.classList.add('active')
$firstWord.querySelector('letter').classList.add('active')

const intervalId = setInterval(() => {
currentTime--
$time.textContent = currentTime

if (currentTime === 0) {
clearInterval(intervalId)
gameOver()
}
}, 1000)
}

function initEvents() {
document.addEventListener('keydown', () => {
$input.focus()
if (!playing) {
playing = true
const intervalId = setInterval(() => {
currentTime--
$time.textContent = currentTime

if (currentTime === 0) {
clearInterval(intervalId)
gameOver()
}
}, 1000)
}
})
$input.addEventListener('keydown', onKeyDown)
$input.addEventListener('keyup', onKeyUp)
$button.addEventListener('click', initGame)

}

function onKeyDown(event) {
Expand Down

0 comments on commit 6406ef8

Please sign in to comment.