Search code examples
node.jswhile-looptimer

setTimeout() in node.js wont take effect inside listener


Im trying to setup a simple server to poke a database every 5 seconds and fetch data from it.

I've built a dummy function called "check_pairs" just to make sure that the setTimeout function is working, but it doesn't seems to make the timeout, it just prints without delaysenter image description here

any idea why is that? Im also importing the current imports and using node version v19.6.0

Thanks in advance :)


Solution

  • You don't wait for the setTimeout promise to resolve. Try this:

    async function check_pair() {
      while (true) {
        console.log("Checking pairs");
        await setTimeout(1000);
      }
    }