Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
how to use both timeout and break inside for loop in javascript

As per below code timeout not working properly how to solve this problem.

for (let i = 0; i < 4; i++) {
  if (socket.isConnected() == true) {
    connectCall([]);
    break;
  } else {
    setTimeout(() => {
      console.log("Call-1:");
    }, 1000);
  }
}

Here SetTimeout not working properly every time hold for some time. my concern is that when condition is match break loop and not match then hold for some time.if any other way to done it then please send me proper solution. if its done from while loop or any other loop then its also accepted.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

setTimeout is working properly, it delays the execution of the console.log for 1 second but this is happening asynchronous.

As you can see in this example all logs happen directly after 1 second:

for(let i = 0; i < 4; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}

If you want to "sleep" for one second in your loop you have to wait for the setTimout.

You can do this with a Promise for example:

(async () => {
  const socket = {
    isConnected: () => false
  }

  for (let i = 0; i < 4; i++) {
    if (socket.isConnected()) {
      connectCall([]);
      break;
    } else {
      await new Promise(res => {
        setTimeout(() => {
          console.log(`Call-${i}:`);
          res();
        }, 1000);
      });
    }
  }
})();

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!