So in this example, if I don't nest the
box.style.animation = 'myanimation 3s'
inside of the setTimeout, then the code doesn't work. But when I run it like this, with a timeout delay of ZERO, it works. Originally I thought that maybe it was an execution timing error, so I set the Timeout delay to 50, but I got curious and tried lower amounts until I got to zero, and it still ran. Essentially I was just trying to implement an animation every time the element is clicked. Is there a better/safer workaround for this? Also, for curiosity, what is the difference between running that line of code directly after the 'if' statement versus nesting it in a setTimeout with a delay of 0? I'm using Firefox with Ubuntu LTS 20.04
edit: I should add, if I don't nest inside the setTimeout function, the animation will run the first time, but not any subsequent time. But when I run the code as shown, it runs everytime.enter image description here
const box = document.querySelector('.box')
box.addEventListener('click', function() {
if(box.style.animation){
box.style.animation = ''
}
setTimeout(function() {
box.style.animation = 'myanimation 3s'
}, 0)
})
EDIT: Another answer I came across on reddit, is to listen for an animationend event, such as:
const box = document.querySelector('.box')
box.addEventListener('click', function() {
box.style.animation = 'myanimation 3s'
})
box.addEventListener('animationend', function() {
box.style.animation = ''
})