首页 > 解决方案 > 如何使用循环间隔 10 秒发送消息?

问题描述

在我的代码中,消息每隔几秒发送一次。如何通过消息推进而不是一遍又一遍地发送相同的消息?

第一条消息发送成功,第二条消息需要比第一条延迟几秒钟发送。

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

标签: javascriptnode.jsiterationsettimeout

解决方案


这是每 3 秒运行一次的简单循环。您可以扩展此代码以从数组或其他函数中读取您的消息(可能使用 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();


推荐阅读