I saw a tutorial on youtube of how to make a speed typing game, it works fine, but the timer starts to count once the page is loaded/or the new quote is rendered. I want add a new function to make the timer start only when the first character is typed, I could make it stay in 0 with the .innerText = 0, but I'm not being able to make it start when I type the character, what is wrong with the function I created?(The renderNewQuote and startTimer functions are working well, just have to make this resetTimer function I created work)
function resetTimer() {
timerElement.innerText = 0
quoteInputElement.addEventListener('onkeydown', () => {
onkeydown.startTimer()
})
}
Edit: That's part of the original code, where I want to implement that functionally I said above:
async function renderNewQuote() {
const quote = await getRandomQuote()
quoteDisplayElement.innerHTML = ''
quote.split('').forEach(character => {
const characterSpan = document.createElement('span')
characterSpan.innerText = character
quoteDisplayElement.appendChild(characterSpan)
})
quoteInputElement.value = null
resetTimer() // Here was the startTimer() function, where I changed to the one that I created
}
function resetTimer() {
timerElement.innerText = 0
quoteInputElement.addEventListener('input', () => {
onkeydown.startTimer()
})
}
let startTime
function startTimer() {
timerElement.innerText = 0
startTime = new Date()
setInterval(() => {
timer.innerText = getTimerTime()
}, 1000)
}
CodePudding user response:
In your resetTimer() function do for example this:
function resetTimer() {
timerElement.innerText = 0
quoteInputElement.addEventListener('input', (event) => {
if(event.target.value.length===1) startTimer()
})
}
The solutions before haven't been working since they are missing the condition. Because of this, the startTimer() function was called over and over starting from number 0.
CodePudding user response:
Javascript has a wonderful event listener called input
function resetTimer() {
timerElement.innerText = 0
quoteInputElement.addEventListener('input', () => {
startTimer()
})
}