Please try and run the following snippet, then click on the box.
const box = document.querySelector('.box')
box.addEventListener('click', e => {
if (!box.style.transform) {
box.style.transform = 'translateX(100px)'
new Promise(resolve => {
setTimeout(() => {
box.style.transition = 'none'
box.style.transform = ''
resolve('Transition complete')
}, 2000)
}).then(() => {
box.style.transition = ''
})
}
})
.box {
width: 100px;
height: 100px;
border-radius: 5px;
background-color: #121212;
transition: all 2s ease;
}
<div class = "box"></div>
What I expect to happen:
- Click happens
- Box starts translating horizontally by 100px (this action takes two seconds)
- On click, a new
Promise
is also created. Inside saidPromise
, asetTimeout
function is set to 2 seconds - After the action is completed (two seconds have elapsed),
setTimeout
runs its callback function and settransition
to none. After doing that,setTimeout
also revertstransform
to its original value, thus rendering the box to appear at the original location. - The box appears at the original location with no transition effect problem here
- After all of those finish, set the
transition
value of the box back to its original value
However, as can be seen, the transition
value does not seem to be none
when running. I know that there are other methods to achieve the above, e.g. using keyframe and transitionend
, but why does this happen? I explicitly set the transition
back to its original value only after the setTimeout
finishes its callback, thus resolving the Promise.
EDIT
As per request, here's a gif of the code displaying the problematic behaviour: