Node js loop Time

Asked

Viewed 149 times

1

I am performing these functions below in a for. The functionality is almost doing what I wish, but I wonder if it would be like after running const q = await clientOut.write(p[i]), wait at least 3 seconds before continuing for. It is possible to do this?

const dadosMsg = await x.getValueMsg();

for(var i =0;i<dadosMsg.length;i++){

      c = await xmlTemplates.xml_16_begin(dadosMsg[i]);  

      const b = await clientOut.write(c);
      console.log(b+' >>>>>>>>>>Entrada');    
      const p = await xmlTemplates.xml_16_end();

      const q = await clientOut.write(p[i])
      console.log(q+' >>>>>>>>>>Saida');
}

1 answer

2

You can create a function wait, that returns a promise that will be resolved after a certain time.

Something like that:

function wait(time = 0) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}

// Usando em uma função assíncrona qualquer:
async function main() {
  console.log('Começo.');
  await wait(1500); // Espera 1,5 segundo (1500ms).
  console.log('Fim.');
}

main();

If you are using Node and want to install a package to not implement it manually, you can use the waait.

Browser other questions tagged

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