0
votes

I have a toggle button true/false on my extensions popup.html page. The button has a 0.4 transition animation. Sometimes when opening popup page I could see the button sliding into its final position so I set default transition time in CSS to zero and used JS to change it back to 0.4 after popup.html loaded.

My init function reads the value from chrome storage and sets the button in proper position. After that it adds a new class to my checkbox which has transition time set to 0.4s. It works if I wrap my last step in setTimeout with 0ms but if I don't use setTimeout and leave the querySelector in same place the style gets applied so fast that I can once again see it happening while opening popup.html. My question is why is this happening? Shouldn't this same thing happen with setTimeout at zero as well?

function init(){
   chrome.storage.sync.get(['switchState'], function(result) {
    var switchState = result.switchState;
    document.querySelector("input[type='checkbox']").checked = switchState;
    setTimeout(() => {
      document.querySelector(".slider").classList.add("animated-slider");
    }, 0);
   });
}
init();

.slider:before {
   position: absolute;
   content: "";
   height: 25px;
   width: 25px;
   left: 2.5px;
   bottom: 2.5px;
   background-color: white;
   transition: 0s;
   border-radius: 25px;
}
.animated-slider:before {
   transition: 0.4s;
}
1
cant you just initialy hide it with css ? - john Smith
@johnSmith I could hide it but then the popup.html would load without visible button at all and instead of transition animation "popping" I would have whole-button "popping". The problem is successfully solved with setTimeout(), I just wanted to understand why timeout at zero was not ran at the same time as without using setTimeout at all. - miyagisan
A zero timeout is never actually a zero in modern browsers. It could be even a second if the currently executed event loop tick takes so long. - wOxxOm

1 Answers

2
votes

When you use setTimeot, your function not execute instantly. it get to the queue of asynchronous calls and will be executed when the engine not be busy with synchronous code. So this delay give some time to your css works. If you want to have control in this situation you need to use transitionend event