首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用循环间隔10秒发送消息?

如何使用循环间隔10秒发送消息?
EN

Stack Overflow用户
提问于 2021-08-01 05:05:59
回答 3查看 298关注 0票数 0

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

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

代码语言:javascript
运行
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-08-01 06:01:24

我认为,应该使用setInterval而不是setTimeout来在定义的时间段之后重复执行函数。

代码语言:javascript
运行
复制
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);

票数 0
EN

Stack Overflow用户

发布于 2021-08-01 05:13:38

这是一个简单的循环,每3秒运行一次。您可以扩展此代码,以便从数组或其他函数中读取消息(可以使用yield)

代码语言:javascript
运行
复制
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();

票数 1
EN

Stack Overflow用户

发布于 2021-08-01 05:38:06

Bharat提供了正确的答案:)

代码语言:javascript
运行
复制
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();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68607651

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档