Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

87
Visualizações
Avoid DOM changes being merged together

My project includes a function that may take a noticable time to complete on weaker devices, so I would like to display a loading icon to the user while this is happening. Said function performs a bunch of string concatenation and then a single write to the DOM.

My code looks something like this:

function onclick() {
    showLoader();
    
    longDOMWriteCall();
    
    hideLoader();
}

function showLoader() {
    loader.classList.remove("hidden");
}

function hideLoader() {
    loader.classList.add("hidden");
}

It appears as if for some reason the browser runs the show and hide calls, as well as the write call from the function, at the same time, causing the loader to never appear in the first place, despite the code being synchronous. Even making the operation asynchronous using promises produces the same result:

function onclick() {
    showLoader();
    
    longDOMWriteCall().then(hideLoader);
}

How can I stop this from happening, such that the loader appears, the function does its thing, then the loader disappears again? The effect is unnoticable on a high-end device, but the low-end device I've tested with can take up to half a second to complete the call.

Fiddle: https://jsfiddle.net/Emosewaj/u07o8ybj/33/

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Run the code asynchronously with setTimeout().

In the example below I have a long timeout so the effect is visible on normal computers. You can use 0 on the real device.

const loader = document.getElementById("loader");
const container = document.getElementById("container");

function clickFuncAsync() {
  showLoader();

  longDOMWriteCallAsync().then(hideLoader);
}

function longDOMWriteCallAsync() {
  console.log("Running async");
  return new Promise(resolve => {
    setTimeout(() => {
      let html = "";

      for (let i = 0; i < 5; i++) {
        html += "<div>Content</div>";
      }

      container.innerHTML = html;
      resolve();
    }, 1000);
  });
}

function showLoader() {
  loader.classList.remove("hidden");
}

function hideLoader() {
  loader.classList.add("hidden");
}
#loader {
  height: 32px;
  width: 32px;
}

#loader.hidden {
  display: none;
}
<button onclick="clickFuncAsync()">
    Run Async
</button>

<div id="loader" class="hidden">
  <img src="https://picsum.photos/32/32">
</div>

<div id="container">
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

const loader = document.getElementById("loader");
const container = document.getElementById("container");

function clickFunc() {
  showLoader();
  setTimeout(()=> {
    longDOMWriteCall();
    hideLoader();
  }, 1)
}

function clickFuncAsync() {
  showLoader();
  setTimeout(()=> {
    longDOMWriteCallAsync()
    hideLoader()
  }, 1)
}

function longDOMWriteCall() {
    console.log("Running sync");
    let html = "";
    for (let i = 0; i < 50000; i++) {
        html += "<div>Content</div>";
    }
    container.innerHTML = html;
}

function longDOMWriteCallAsync() {
    console.log("Running async");
    return new Promise(resolve => {
        let html = "";
        for (let i = 0; i < 50000; i++) {
            html += "<div>Content</div>";
        }
        container.innerHTML = html;
        resolve();
    });
}

function showLoader() {
  loader.classList.remove("hidden");
  console.log('sdfds')
}

function hideLoader() {
console.log('vvvvv')
    loader.classList.add("hidden");
}
#loader {
    height: 32px;
    width: 32px;
}

#loader.hidden {
    display: none;
}
<button onclick="clickFunc()">
    Run
</button>
<button onclick="clickFuncAsync()">
    Run Async
</button>
<div id="loader" class="hidden">
    <img src="https://picsum.photos/32/32">
</div>


<div id="container">
</div>

You can try wit timeout:

showLoader();
  setTimeout(()=> {
    longDOMWriteCallAsync()
    hideLoader()
  },1)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda