Wait for function to finish using async/await keywords As you already know from the Promise explanation above, you need to chain the call to the function that returns a Promise using then/catch functions. The await keyword allows you to wait until the Promise object is resolved or rejected: await first(); second();
In the minimal example below, the replacement of old content is deferred by setTimeout
to give the user time to finish viewing it. In the meantime, new content is being prepared so as to avoid blocking the user interface during a potentially expensive task.
var div = document.getElementById('wrapper');
var newContent = document.createElement('ul');
setTimeout(function() {
var header = div.firstElementChild;
header.innerHTML = 'New Content';
header.nextElementSibling.remove();
div.appendChild(newContent);
}, 2000);
// Make new content while we wait
[1, 10, 100, 1000].forEach(function(x) {
var li = document.createElement('li');
li.innerHTML = 'Factorial of ' + x + ' is ' + factorial(x);
newContent.appendChild(li);
});
function factorial(num) {
if (num === 0) {
return 1;
} else {
return (num * factorial(num - 1));
}
}
<div id='wrapper'>
<h1>Old content</h1>
<p>Read it before it's gone.</p>
</div>
My concern with this approach is that it does not seem to handle newContent
not being ready when the replacement is due to take place. I am also uncertain if this approach will block the user interface or if the task used by setTimeout
will be executed concurrently.
How can I ensure that the user interface is not blocked while executing a potentially expensive task and immediately using it upon completion?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With