Is there any way to stop an interval based on a specified message content? Or make the users stop the interval first before starting a new interval?
Here is the code for starting an interval:
const ms = require('ms')
let interval;
function isNumeric(str) {
return !isNaN(str) && !isNaN(parseFloat(str));
}
module.exports = {
name: 'interval',
aliases: ['int'],
run: async (client, message, args) => {
let time = args[0];
if(!time) return message.reply('Please enter the duration of message interval!').then(msg => {
setTimeout(() => {
msg.delete()
}, 5000)
})
.catch()
let reason = args.slice(1).join(' ');
if(!reason) return message.reply('Please enter a message!').then(msg => {
setTimeout(() => {
msg.delete()
}, 5000)
})
.catch()
interval = setInterval(function() {
message.channel.send(reason)
.catch(console.error);
}, ms(time));
},
stopInterval() {
if(interval) {
clearInterval(interval);
}
}
}
The specified message content would be the
let reason = args.slice(1).join(' ');
As for the code for stopping the interval:
const stopInt = require('./interval');
module.exports = {
name: 'stopinterval',
aliases: 'stopint',
run: async (client, message, args) => {
message.channel.send("Message reminder has been stopped.");
stopInt.stopInterval();
}
}
I also have a problem which if I use the interval twice, I can only stop the last interval I created and couldn't stop the first one.
You could use a Set or an array to keep track of a list of intervals:
const ms = require("ms");
const intervals = new Set()
function isNumeric(str) {
return !isNaN(str) && !isNaN(parseFloat(str));
}
module.exports = {
name: "interval",
aliases: ["int"],
run: async (client, message, args) => {
let time = args[0];
if (!time)
return message
.reply("Please enter the duration of message interval!")
.then((msg) => {
setTimeout(() => {
msg.delete();
}, 5000);
})
.catch();
let reason = args.slice(1).join(" ");
if (!reason)
return message
.reply("Please enter a message!")
.then((msg) => {
setTimeout(() => {
msg.delete();
}, 5000);
})
.catch();
intervals.add(setInterval(function () {
message.channel.send(reason).catch(console.error);
}, ms(time)));
},
stopInterval() {
for (const interval of intervals) {
intervals.delete(interval);
clearInterval(interval);
}
},
};
(I toke the liberty to format your code using prettier)
Unrelated to your question but I noted:
async / await with .then / .catch.catch() calls should be removed