简体   繁体   中英

Difference between setTimeout with 0ms and not using setTimeout in my extension's popup.html

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM