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

143
Vistas
It is not possible to get an index in an asynchronous loop/function

I tried to get an index that I don't get right away, but I don't know how to do it correctly.

I created a quick example where there are 2 buttons and accessing them. But I always get only 0 index.

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));  
const btns = document.querySelectorAll('button') 
const btnsArr = [...btns];
let index = 0; 

const asyncTestFunction = async () => { 
  for (let i = 0; i<2; i++) { 
   await sleep(5000); 
   index = i; 
   console.log(index, 'loop'); 
  }
} 

asyncTestFunction(); 

btnsArr[index].addEventListener('click', () => { 
  console.log(index, 'index - EventListener')
}) 
<html>
  <head>
    <meta charset="UTF-8">
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
  </head>
  <body>
    <button >My other page click1</button>
    <button >My other page click2</button> 
    <script src="script.js"></script>
  </body>
</html>

I don't get the second button event.

This is due to time, I'm not waiting for the index to be received because I don't know how to do it correctly.

about 4 years ago · Juan Pablo Isaza
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