javascript - 如何使用循环间隔 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
解决方案
这是每 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();
推荐阅读
- android - 错误 E/RecyclerView:未连接适配器;在 holder.itemView.setOnClickListener 下实现意图时跳过布局问题
- c++ - 使用没有缓冲区变量的 sprintf
- python - 如何使用 dlib 在 python 中进行图像聚类?
- nlp - 在哪里可以找到日语 - 汉语词典的资源
- ruby-on-rails - Rails 捆绑包无法安装 gem ffi
- google-apps-script - Google Appscript:将文本放在特定列的第一个空行中
- eclipse - 如何使用 spark (Eclipse) 从 Elasticsearch 读取数据并将其转换为表格格式
- c++ - Visual Studio 中代码块中的编译器标志是否有类似物?
- android - com.twitter.sdk.android.core.TwitterApiException:HTTP 请求失败,状态:400
- html - 我做了一个可悬停的菜单,效果很好。但我想对其进行一些更改并使其成为可点击的下拉菜单