Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!