Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
async wait for element to load in so i can find it with jquery

i don't really understand async. i have a function like this:

function getTeam() {
    let sir = setInterval(() => {
        const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir)
          return firstTeam.trim()
        }
    }, 100)
}

im not js master. i just want to get that element when it loads in, this code is running in a userscript and // @run-at document-idle doesnt help either. i knew i would have to get into async js promises callbacks and whatever someday but i really dont understand how it works after pages of docs and other stackoverflow. when i console.log this function it will print undefined once then if i have a console.log inside the if it will print the actual team name. how do i wait for that result

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Answer regarding the javascript language part if the question

You could modify your code to the following (but don't - see further below - I'm just providing this as your StackOverflow tags included async/await):

async function getTeam() {
    return new Promise(resolve => {
      const sir = setInterval(() => {
        const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir);
          resolve(firstTeam.trim());
        }
      }, 100);
    });
}

// ... and then anywhere else in your code:
doSomethingSynchronous();
const team = await getTeam();
soSomethingSynchronousWithTeam(team);

Note that this will only work with modern browsers supporting >= ECMAScript 2017: https://caniuse.com/async-functions (but luckily that's most by now!)

Answer regarding the implicit "howto wait for an element part"

... you really shouldn't actively wait for an element because this is unnecessarily heavy on the CPU. Usually you'll have some kind of event that informs you as soon as the element you're waiting for has been created. Just listen for that and then run your code.

What to do, if there's currently no such event:

  • If you're in control of the code creating the element, then trigger one yourself (see https://api.jquery.com/trigger/ for example).
  • If the element is created by a third party lib or by something else you cannot easily modify, you could use a MutationObserver (see this StackBlitz answer to a related question) and run your getTeam code only whenever something has changed instead of every 100ms (smaller impact on performance!)
about 4 years ago · Juan Pablo Isaza Denunciar

0

function getTeam() {
    let sir = new Promise((res, rej) => {
    const teamsGrid = $('[class*="teamsgrid"]').find("p");
        const firstTeam = $(teamsGrid[0]).text();
        if (firstTeam != '') {
          clearInterval(sir);
          res(firstTeam.trim());
        }
    });
    return sir();
}

From what I understood, you are looking for firstTeam. Also, we assume that there is always firstTeam, so there isnt a case when there would be no team name. I am not sure where you are making a req that will take time to process honestly from this code. So far it looks that sync function should do just fine. Are you reaching out to any API?

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can make it async if you want, but the main part us going to be using events instead. There is a special object called mutation observer. It will call a function you give it any time there's a change in the element you're observing.

Check the mutation observer docs to understand the code below: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver

Without knowing much about your HTML, I can say as much as this should work:

function getTeam() {
  const teamsGrid = $('[class*="teamsgrid"]').find("p");
  const firstTeam = $(teamsGrid[0]).text();
  if (firstTeam != '') {
    return firstTeam.trim()
  }
}

function getTeamWhenAvailable() {
  // returning a promise allows you to do "await" and get result when it is available
  return new Promise((resolve, reject) => {
    // furst try if element is available right now
    const teamText = getTeam();
    if(teamText) {
      // resolve() "returns" the value to whoever is doing "await"
      resolve(teamText);
      // resolve does not terminate this function, we need to do that using return
      return;
    }
      

    // Mutation observer gives you list of stuff that changed, but we don't care, we just do our own thing
    const observer = new MutationObserver(()=>{
          const teamText = getTeam();
          if(teamText) {
            // stop observing
            observer.disconnect();
            // resolve the value
            resolve(teamText);
          }
    });
    observer.observe(document.body, { childList: true, subtree: true };
  })
}

// usage, the extra brackets around the lambda cause it to invoke immediatelly

(async () => {
  console.log("Waitinf for team...");
  const teamName = await getTeamWhenAvailable();
  console.log("Result team name: ", teamName)
})();

Now you might wanna narrow the scope of the mutation observer, in the example above it watches the entire document. Try to instead observe the deepest element that you can rely on not being removed.

If you need to receive team name multiple times, I think you should just go with the obsever alone without the async stuff.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda