【问题标题】:How to use a loop to send messages 10 seconds apart?如何使用循环间隔 10 秒发送消息?
【发布时间】:2021-10-06 23:37:08
【问题描述】:

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

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

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

【问题讨论】:

  • 简单的设置超时应该可以工作
  • 嘿@Bharat,您知道如何将其写入代码吗?
  • 消息是否存储在数组中?
  • @denzaa 欢迎来到 SO!当前代码到底有什么问题?
  • 第二条消息在哪里?消息是如何存储的?例如,您可以在每次循环运行时推进一组消息。

标签: javascript node.js iteration settimeout


【解决方案1】:

这是每 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();

【讨论】:

  • 如果这是您要找的,请接受回答,否则请告诉我您要找什么?
  • 从哪里得到消息?一旦你决定了那部分,你所要做的就是用 client.action('mrpooski',); 替换这段代码。读出yield,我看到这里也是gr8
【解决方案2】:

Bharat 提供了正确答案:)

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();

【讨论】:

    【解决方案3】:

    我觉得,setInterval 应该用于在定义的时间段后重复执行一个函数,而不是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);

    【讨论】:

    • @denzaa 请接受答案,以便将来对其他人有所帮助。
    猜你喜欢
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 2017-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多