css transition is not trigger by add classes in a same function

Viewed 1969

when I click the window, CSS transition is not trigger.

const div = document.querySelector('div');
window.onclick = function() {
  div.classList.add('fade');
  div.classList.add('in');
}
.fade {
  opacity: 0;
}

.fade.in {
  transition: opacity 2s linear;
  opacity: 1;
}
<div>aaaa</div>

then I change the script, use setTimeout to add the second class in, it works.

const div = document.querySelector('div');
window.onclick = function() {
  div.classList.add('fade');
  setTimeout(function() {
    div.classList.add('in');
  });
}
.fade {
  opacity: 0;
}

.fade.in {
  transition: opacity 2s linear;
  opacity: 1;
}
<div>aaaa</div>

so I think, is nees a period time between CSS property change can trigger CSS transition?

so i add the time between add classes. it also not work.

<script>
window.onclick = function(){
    div.classList.add('fade');
    for(var i=0;i<10000; i++){
        console.log(i);
    }
    div.classList.add('in'); 

}
</script>

why change classes in a same function can not trigger a css transition?

3 Answers
Related