0

I have a delay function that goes like

const delay = (ms: number) => new Promise(res => setTimeout(res, ms));

Inside a for each I am trying to wait X seconds (Where x is a random number coming from randomIntFromInterval but it seems to execute all my code at once

function randomIntFromInterval(min: number, max: number) { // min and max included 
    return Math.floor(Math.random() * (max - min + 1) + min)
  }  
const array = ['aa', 'bb', 'cc']
 array.forEach(
            async (item) => {
                const randomTimer = randomIntFromInterval(40000, 90000);
                // EXTRA LOGIC HERE
                await delay(randomTimer); // THIS IS NOT WAITING PROPERLY
            }
        ) 
  • 1
    Does this answer your question? [Combination of async function + await + setTimeout](https://stackoverflow.com/questions/33289726/combination-of-async-function-await-settimeout) – Michael M. Sep 17 '22 at 18:04
  • `await delay(randomTimer); // THIS IS NOT WAITING PROPERLY` — That's the last line of code in the function. There's nothing waiting for the delay to finish except the final settling of the promise returned by the `async (item)` function (which `forEach` pays no attention to). – Quentin Sep 17 '22 at 18:06
  • @MichaelM.not reallY I tried to wrap in a promise like this but it seems to be wron – kkiiooppll Sep 17 '22 at 18:32
  • const foo = async (users: any) => { users.forEach(async (user: any) => { // LOGIC HERE }); const randomTimer = randomIntFromInterval(40000, 90000); await delay(randomTimer); }; while (i < slicedArray.length) { var [user]: any = await Promise.all([foo(slicedArray)]); // other code } – kkiiooppll Sep 17 '22 at 18:36

0 Answers0