I ask for help finding the best solution making loops non-blocking the UI.
Given example below, I would expect that the button text changes first to 'I am running'. Instead, the browser get's blocked until the loop finishes and afterward the button text changes.
function addUpTo(n) {
let total = 0;
for (let i = 1; i <= n; i++) {
total += i;
}
alert('loop done')
return total;
}
const button = document.getElementById('button__test')
button.addEventListener("click", function(){
button.firstChild.data = 'I am running'
addUpTo(1000000000);
} );
<button id="button__test">Click me</button>
Question:
button.firstChild.data = 'I am running'comes first in code, why is the loop 'gaining the upper hand' is it somehow of higher priority or hoisted?I've tried with promises, async/await, timeout and this interesting solution passing a function as worker without luck. What is the suggested crossbrowser way in 2019 to solve this issue?
EDIT: Find here my fiddle trying to run the loop as worker: https://codepen.io/t-book/pen/VoqNPY?editors=1011 The reason I have choosen to use it as blob is as I'm using es6 modules. (As far as I know it's not possible yet to use an importes module as worker)