Why doesn't the background color change first?
I believe the code is working correctly. However, after setting the background color, you immediately lock up the processor with an extremely long loop. The browser does not have time to color the background before it gets frozen calculating the sum of 1 to a billion. While the property of the background color will be set before the function, the actual re-rendering takes a non-zero amount of time.
You can see this by setting a delay before letting the promise return. In this case (or at least on my processor anyway), the background will turn red first.
'use strict';
const sum = num => {
let acc = 0;
while (num) {
acc = acc + num;
num = num - 1;
}
return acc;
};
new Promise((res, reject) => {
document.querySelector('body').style.backgroundColor = 'red';
setTimeout(res, 250);
}).then(() => {
const res = sum(1000000000);
console.log(res);
});