Here's the scenario... I add an element to the DOM that has an initial class to have 0 opacity and then add a class to trigger the opacity transition to 1 - a nice simple fade-in. Here's what the code might look like:
.test {
opacity: 0;
transition: opacity .5s;
}
.test.show {
opacity: 1;
}
const el = document.createElement('div')
el.textContent = 'Hello world!'
el.className = 'test' // <div class="test">Hello world!</div>
document.body.appendChild(el)
Now to trigger the fade-in, I can simply add the show
class to the element:
setTimeout(() => {
el.classList.add('show')
}, 10)
I'm using a setTimeout because if I don't, the class will be added immediately and no fade-in will occur. It will just be initially visible on the screen with no transition. Because of this, I've historically used 10ms for the setTimeout and that's worked... until now. I've run into a scenario where I needed to up it to 20ms. This feels dirty. Does anyone know if there's a safe time to use? Am I missing something about how the DOM works here? I know I need to give the browser time to figure out layout and painting (hence the setTimeout), but how much time? I appreciate any insight!