How do I block processing of other messages in the event loop during a CSS transition?

Here's an example:

document.getElementById("myDiv").addEventListener("mouseover", function() {
  setTimeout(function() {
    console.log(1)
  }, 1)
})
      

div {
  transition: all 2s;
  position: fixed;
  top: 10px
}
div:hover {
  top: 100px;
}
      

<div id="myDiv">123</div>
      

Run codeHide result


What I want to do is show the CSS animation first. And when this animation is over, run the javascript function function() {console.log(1)}

. However, when I run this snippet, I found that it function() {console.log(1)}

runs before the animation ends.

Does this mean that the CSS transition is independent of the message queue (event loop). Does anyone have any ideas on how to block other processing messages in the message queue (event loop) until the CSS transition is complete?

I know it transitionend

works if you want to register a new callback, but what if there is already code registered in the message queue setTimeout

. I have no idea how to temporarily block them.

+3


source to share


1 answer


You can use the transitionend event , but note that it will fire when the mouse is entered and when the mouse is left



var div = document.getElementById("myDiv");
div.addEventListener("transitionend", function() {
  console.log(1)
})
      

div {
  transition: all 2s;
  position: fixed;
  top: 10px
}
div:hover {
  top: 100px;
}
      

<div id="myDiv">123</div>
      

Run codeHide result


+2


source







All Articles