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

157
Visualizações
Racing condition in JavaScript

In my webpage, I have some HTML elements and some JavaScript functions that act on them. I want my HTML elements to be fully loaded before JavaScript functions run.

For example, I have <div id="buttonsection"></id>. I want buttonsection div to load first before my updateButtonSection() run.

At first, I was doing this by using timeout:

setTimeout("updateButtonSection()", 1500);

However, if timeout is too short, the updateButtonSection will run before buttonsection div finish loading. But if timeout is too long, users with good internet speed will have not have a good experience since users have to wait on the timeout.

So then I decided to check if div is loaded before running the JavaScript function.

function updateMarkerButton(){

  //if elements not loaded, wait 1 second and then call itself 
  if(document.getElementById('buttonsection') === null ){
    setTimeout("updateMarkerButton()", 1000);
  }else{
    ....
  }

This mostly works until I find out if I am already on the webpage with everything loaded, if I call my refresh function, then updateMarkerButton will run immediately because the current buttonsection div is already loaded so document.getElementById('buttonsection') is not null; thus updateMarkerButton will not wait for buttonsection div to reload before it runs.

Any suggestion on how else I can prevent this racing condition so JavaScript functions only run after HTML elements finish loading?

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

0

If the script tag comes after the element then it will ensure the script runs after the element is created
That's why there is a practice to put the script tags at the end of the body

about 4 years ago · Juan Pablo Isaza Relatório

0

The window load event fires when the HTML is fully loaded:

window.addEventListener('load', (event) => {
  console.log(`I'm ready for you now, sweetheart.`);
});
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