denzaa
denzaa

Reputation: 3

How to use a loop to send messages 10 seconds apart?

In my code, the message sends every few seconds. How do I make it advance through messages instead of sending the same message over and over?

The first message is sent successfully, the second message needs to be sent with a few seconds delay from the first one.

const tmi = require('tmi.js');

var value = true;

const options = {
  options: {
    debug: true,
  },
  connection: {
    cluster: 'aws',
    reconnect: true,
  },
  identity: {
    username: 'yessirski69', //username of the bot
    password: 'yolopoo', //login token of the bot
  },
  channels: ['mrpooski'], // the channel you are targetting
};

const client = new tmi.client(options);

client.connect();

var i = 1; //  set your counter to 1

function myLoop() { //  create a loop function
  setTimeout(function() { //  call a 3s setTimeout when the loop is called
    client.action('mrpooski', 'Hello This is the first message'); //  your code here
    i++; //  increment the counter
    if (i < 1000) { //  if the counter < 10, call the loop function
      myLoop(); //  ..  again which will trigger another
    } //  ..  setTimeout()
  }, 3000)

}

myLoop(); //  start the loop

Upvotes: 0

Views: 1224

Answers (3)

Salvino D&#39;sa
Salvino D&#39;sa

Reputation: 4506

I feel, setInterval should be used for executing a function repeatedly after a defined period instead of setTimeout.

let messages = ["Message 1", "Message 2", "Message 3", "Message 4", "Message 5", "Message 6"];
let counter = 0;
let timer;

function myLoop() {
  var date = new Date();
  if (!messages[counter]) return clearInterval(timer);
  console.log(date + " : " + messages[counter]);
  counter++;
}


timer = setInterval(myLoop, 3000);

Upvotes: 0

denzaa
denzaa

Reputation: 3

Bharat provided the correct answer :)

var messages = ["Message 1","Message 2","Message 3","Message 4","Message 5","Message 6"];
var counter = 0;

function myLoop() {  
var date = new Date();
console.log(date + " : " + messages[counter++]);

setTimeout(myLoop, 3000);

}


myLoop();

Upvotes: 0

Bharat
Bharat

Reputation: 1205

Here is simple loop that runs every 3 seconds. You can extend this code to read your message from array or some other function (may be use yield)

var messages = ["Message 1","Message 2","Message 3","Message 4","Message 5","Message 6"];
var counter = 0;

function myLoop() {  
var date = new Date();
console.log(date + " : " + messages[counter++]);

setTimeout(myLoop, 3000);

}


myLoop();

Upvotes: 1

Related Questions