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.

Answer

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);
      });
    }
  }
})();