简体   繁体   中英

How to add Sleep in Node.js after executing command?

Basically this is a chat bot for Twitch.tv. Currently, it replies to someone in the chat when they say "Hello". I'd like to add a Sleep for 2 seconds after the bot replies with hello, so it doesn't flood the chat. I have tried setTimeout/setInterval but those put the 2 second delay BEFORE it replies to the person. Cheers.

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

process.setMaxListeners(0);

var options = {
options: {
    debug: true
},
connection: {
    cluster: "aws",
    reconnect: true
},
identity: {
    username: "",
    password: ""
},
channels: [""]
};

var client = new tmi.client(options);
client.connect();

client.on('chat', function(channel, user, message, self) {
if(message === "Hello") {
    client.action("", "@" + user['display-name'] + ", Welcome!");
}});
var canSendMessage = true;
client.on('chat', function(channel, user, message, self) {
if(message === "Hello" && canSendMessage ) {
canSendMessage = false;
client.action("", "@" + user['display-name'] + ", Welcome!");
setTimeout(function(){ canSendMessage = true }, 2000);
}});

You can try this (Not tested). The variable canSendMessage will block the bot from writing if it is not reseted after 2000ms (2s).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM