Exploring the intricacies of browser rendering mechanics and aiming to optimize various action handling on the same event while understanding how it affects repaints.
Currently, I am attempting to alter the style of a span element (action 1) and perform a more resource-intensive task by incrementing a value in a loop (action 2).
It's puzzling why the change in the span's style is sometimes delayed, especially when the second action is enclosed in a setTimeout function with a 0ms delay.
In contrast, setting the setTimeout delay to 1ms ensures that it does not impede the style change. What causes this difference between delays of 0 and 1?
If we eliminate setTimeout and consolidate all the logic within a promise chain, the span's style change is consistently obstructed. Does this imply that chained microtasks, which operate synchronously, behave akin to a synchronous loop in this scenario? Are they hindering repaints and unsuitable for such optimizations?
P.S. Any recommendations for comprehensive resources addressing optimization of script execution across diverse rendering frames would be greatly appreciated!
document.addEventListener("click", (evt) => {
if (!evt.target.matches("span")) { return; }
evt.target.style.color = "red";
setTimeout(() => {
const loopTimes = 900000;
const result = Array(loopTimes)
.fill()
.reduce((acc, val, i) => {
return acc.then((val) => {
return val + 1;
});
}, Promise.resolve(0));
result.then((endResult) => console.log(endResult));
}, +evt.target.dataset.timeout);
});
<span data-timeout="0">click for red (0ms)</span><br>
<span data-timeout="1">click for red (1ms)</span>