How to wait for my functions to run for it to increment Java Script

Asked

Viewed 40 times

1

I’m making a Java Script code where I need everything inside the for to be executed and then increment the for including a setTimeout. In the current code it executes everything without waiting for the setTimeout to run. Follow code example:

var teste = function () {
    for (let i = 0; i < 100; i++) {
        console.log(i)

        setTimeout(function () {
            console.log("opaopa")
            return
        }, 5000);
    }
}

teste();

In this case you would need the setTimeout to perform afterwards.

  • 1

    Apparently you want to make a process repeatedly. Already tried to see if it would not be more appropriate to use setInterval in place of setTimeout?

  • I will look to know about the setInterval thank you very much!

1 answer

1


You can rewrite this logic as follows

function teste(i) {
  setTimeout(function () {
    if (i < 10)
    {
      console.log("opaopa");
      console.log(i);
      teste(++i);
    }

    return;
  }, 1000);
}

teste(0);

Note that the use of for was deleted, teste received the initial value of i, within the test are made the logics that you presented, increments the i and repeats the process until the stop condition, made by if.

PS: I changed the falores from 5000 to 1000 and from 100 to 10, to be faster to check the logic.

  • The solution caters for the resolution of my problem thank you very much! :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.