title: Is there a better implementation for this async loop in JS?
body: <p>So I'm writing a node.js script that uses Playwright to send different messages at a set interval in a browser. I'm running into an issue with an asynchronous part of the script.</p>
  <p>I initially had it set up in this way</p>
  <pre><code>async start() {
    this.interval = setInterval(async () =&gt; {
      await sendMessages(this.messages);
    }, 1000);
  }
  </code></pre>
  <p>I'm pretty sure the <code>await</code> keyword does nothing here and just executes the next iteration after 1000 ms regardless of whether <code>sendMessages</code> is finished executing or not. This was resulting in messages being double sent when they hit their interval requirement for sending again.</p>
  <p>This code works, and is the subject of my question:</p>
  <pre><code>async start() {
    while (!this.stopFlag) {
      await sendMessages(this.messages);
      await timeout(1000);
    }
  }
  </code></pre>
  <p><code>timeout</code> is a simple function that resolves a Promise after a <code>setTimeout</code> call. However, this seems kind of hacky and I don't really like this way of implementation. Does anyone have a more clever way to execute something like this?</p>
  <p>Here are some more code details:</p>
  <p>Messenger.js</p>
  <pre><code>import Message from './Message.js'
  import { timeout } from './Timeout.js'
  export default class Messenger {
    constructor(messages, page) {
      this.page = page;
      this.messages = messages.map((msg) =&gt; new Message(msg));
      this.stopFlag = false;
    }
  
    async start() {
      while (!this.stopFlag) {
        await this.sendMessages();
        await timeout(1000);
      }
    }
  
    async sendMessages() {
      for (const message of this.messages) {
        if (message.shouldSend()) {
          await message.send(this.page);
        }
      }
    }
  
    stop() {
      this.stopFlag = true;
    }
  }
  </code></pre>
  <p>Message.js</p>
  <pre><code>export default class Message {
    constructor(message) {
      this.text = message.text;
      this.timing = message.timing;
      this.lastSent = null;
    }
  
    async send(page) {
      logMessage(`Sending message &quot;${this.text}&quot; in channel.`);
      await playwrightFunctionToSendMessage();
      this.lastSent = new Date();
    }
  
    shouldSend() {
      // returns a boolean based on this.timing and this.lastSent 
    }
  }
  </code></pre>