Reputation: 1
The timer stops when the mouse hovers over a (.typing) item and the timer resumes when the mouse leaves. That works, but I wanted to remove two classes from separate id's when their respective setTimeout function hits 0.
Heres the code:
let dhaTimeout = {
id: null,
startTime: 0,
remainingTime: 5000,
isPaused: false
}
let stackTimeout = {
id: null,
startTime: 0,
remainingTime: 10000,
isPaused: false
}
function startTimeout(timeout, elementId){
if(timeout.isPaused){
timeout.isPaused = false;
timeout.startTime = Date.now();
timeout.id = setTimeout(() => {
const element = document.getElementById(elementId)
if(element){
element.classList.remove("gone")
} else {
console.log(`Element not found, ${elementId}`)
}
}, timeout.remainingTime)
} else{
timeout.startTime = Date.now()
timeout.id = setTimeout(() => {
const element = document.getElementById(elementId)
element.classList.remove("gone")}, timeout.remainingTime)
}
}
function pauseTimeout(timeout){
if(!timeout.isPaused && timeout.id){
clearTimeout(timeout.id)
timeout.isPaused = true;
timeout.remainingTime = timeout.remainingTime - (Date.now() - timeout.startTime)
timeout.id = null
}
}
function onMouseEnter(){
pauseTimeout(stackTimeout)
pauseTimeout(dhaTimeout)
}
function onMouseLeave(){
startTimeout(stackTimeout)
startTimeout(dhaTimeout)
}
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll(".typing").forEach(element => {
element.addEventListener('mouseenter', onMouseEnter)
element.addEventListener('mouseleave', onMouseLeave)
})
})
startTimeout(stackTimeout, 'full-stack')
startTimeout(dhaTimeout, 'dha')
I'm getting a typeError when the startTimeout function is called for the second time, saying can't read classList when it's null. So I logged the element to see if its there but its not finding it.. but I have nothing removing the individual element so it's not making sense to me how it's not finding the element, maybe the class but the element being gone? I didn't think the html code was necessary as its 3 p elements, first two with the 'typing' class and last two with the 'gone' class. id of 'dha' for the second p and 'full-stack' for the third.
I've tried to add a separate if else for the failure of finding the element to find it again somehow but that lead nowhere.
Upvotes: 0
Views: 16