David
David

Reputation: 1174

change DOM while heavy function is running

I want to display a loading-spinner like this while a heavy function is blocking the main thread.

My code basically looks like this:

image.onload = function onLoad() {
  document.getElementById("loading-spinner").style.display = "block";
  run_heavy_function(this);
};

The loading spinner is only showing up after the function is done. Which is not what i want.

I've come across some solutions using setTimeout and stuff. But that doesn't seem like a good idea to me. What is the right approach to change the DOM in a background process in ES6 using pure javascript?

Upvotes: 1

Views: 93

Answers (1)

Greedo
Greedo

Reputation: 3549

An easy pattern to solve this is event comunication:

const loaderStart = new Event('loaderStart');
const loaderEnd = new Event('loaderEnd');
const spinner = document.getElementById("loading-spinner");

image.onload = function onLoad() {
  spinner.dispatchEvent(loaderStart);
  run_heavy_function(this);
  spinner.dispatchEvent(loaderEnd);
};

spinner.addEventListener('loaderStart', function(){
   this.style.display = "block";
});

spinner.addEventListener('loaderEnd', function(){
   this.style.display = "none";
});

Upvotes: 1

Related Questions