Home > Software engineering >  javascript : I want execute 1 command every X seconds
javascript : I want execute 1 command every X seconds

Time:07-23

Hello, I create a small twitch bot and I want to execute the following condition only once every 100 seconds for example:

if(message.indexOf("emoji") !== -1){
            client.say(channel, `emoji party`);
        }

but as you can see I have other similar conditions so I don't want my whole bot to be paralized for 100 seconds. I want each condition to be time independent

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

const client = new tmi.Client({
    options: { debug: true, messagesLogLevel: "info" },
    connection: {
        reconnect: true,
        secure: true
    },

    // Lack of the identity tags makes the bot anonymous and able to fetch messages from the channel
    // for reading, supervison, spying or viewing purposes only
    identity: {
        username: `${process.env.TWITCH_BOT_USERNAME}`,
        password: `oauth:${process.env.TWITCH_OAUTH_TOKEN}`
    },
    channels: ['channelName']
});
client.connect().catch(console.error);



client.on('message', (channel, tags, message, self) => {
    if(self) return;

        if(message.indexOf("emoji") !== -1){
            client.say(channel, `emoji party`);
        }

        if(message.indexOf("LUL") !== -1){
            client.say(channel, `LUL LUL LUL LUL`);
        }

});

Thanks for you help

CodePudding user response:

You could make use of setInterval(myFunction, 1000);

Take a look at w3schools or MDN for more information

CodePudding user response:

Use SetInterval()

var intervalID = setInterval(myCallback, 500, 'Parameter 1', 'Parameter 2');

function myCallback(a, b)
{
 // Your code here
 // Parameters are purely optional.
 console.log(a);
 console.log(b);
}

From MDN:

setInterval() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.

You can also use clearInterval() to stop the Interval

clearInterval(intervalID);

CodePudding user response:

I think something like that will work for you. Im not sure how to store persistent variable but global might be ok.

global.lastEmojiPartyMs = null; // lets store last called time (milliseconds)

client.on("message", (channel, tags, message, self) => {
  if (self) return;

  if (message.indexOf("emoji") !== -1) {
    const nowMs = Date.now();
    if (
      !global.lastEmojiPartyMs ||
      nowMs - global.lastEmojiPartyMs >= 100 * 1000 // 100 seconds for example
    ) {
      global.lastEmojiPartyMs = nowMs;
      client.say(channel, `emoji party`);
    }
  }

  if (message.indexOf("LUL") !== -1) {
    client.say(channel, `LUL LUL LUL LUL`);
  }
});
  • Related