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.