简体   繁体   中英

How to make a setInterval function in such a way that it can stop and restart?

I've been trying to make a function for my discord.js v12 bot that works in tandem with Disboard. Basically, it's a reminder function that pings a certain role every two hours to remind them to bump the server. I've been trying to work out a way so on !d bump, the bot stops the setInterval function through clearInterval, and starts the setInterval function again. However, I've been receiving an error that says that a certain object is not defined in the script.

Here's my code:

    client.on('message', async message => {
    if (message.content === (`${prefix}setReminder`)) {
        message.channel.send("Interval has been set! Members will be reminded to bump the server every two hours!")
        var role = message.guild.roles.cache.find(role => role.name === "bumping ping")
        let intervalOne = setInterval(() => {
            message.channel.send(`${role} chop-chop! It's time to bump! 😃`)
        }, 7200000);
        
        
    
    }
       
});
    client.on('message', async message => {
        if (message.content === "!d bump") {
            message.channel.send("Thank you for bumping the server. Please check back two hours later to bump the server again.")
            clearInterval(intervalOne)
             .then(setInterval(intervalOne)) | message.channel.send("I have successfully restarted the timer. You will get notified in two hours' time!")
        }



    });

How about this:

module.exports = (client, message) => {
  if(message.content === '!d bump') {
    const pingRole = message.guild.roles.cache.find(role => role.name === 'bumping ping');
    message.channel.send('Thank you for bumping the server. Please check back two hours later to bump the server again.')
    setTimeout(() => message.channel.send(`${pingRole} chop-chop! It's time to bump! 😃`), 7200000);
  }
};

Is that good enough for you?

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