I am creating a bot where every 24 I retrieve categories from a database, and for each category, I will send a post while each post is separated by 1 hour. (After 24 hours send the first post and then one hour later send the next, etc)
My question is how would I set this up while still being able to stop a certain category for the next day. I know setIntervals have an id and I can add them to an array and I can stop the interval with this id. However, I feel like this isn't the most ideal solution.
This is my current solution however I feel like this can be done better either with a node.js package or some other clever work.
let intervalIds = [];
let interval = [];
const categories = ["sad", "toebeans", "meow"]
console.log(`${interval.length}`);
categories.forEach(category => {
let id = interval.push(setInterval(() => {console.log(`Interval for ${category}`)}, 6000000000));
intervalIds.push(`${category}=${id}`)
});
// clearInterval(interval[2]) STOPS 6
console.log(interval);
console.log(intervalIds);
let a = 0;
for (let i = 0; i < intervalIds.length; i ) {
let split = intervalIds[i].split("=");
if (split[0] === "sad") {
clear(a);
break;
}
a ;
}
function clear(a) {
clearInterval(interval[a]);
console.log(interval);
}
I want to be able to call one command that starts all of the timers, and another command that allows a single category to either be turned on or off.
Thanks in advance for the help guys.
CodePudding user response:
better sollution would be make one interval, and in this interval iterate over all categories. Then you can 'set' category as active or inactive:
let categories = new Map();
categories.set("sad", true);
categories.set("toebeans", true);
categories.set("moew", true);
setInterval(() => {
Array.from(categories.keys()).forEach((category) => {
if (categories.get(category)) console.log(`Interval for ${category}`);
//console.log(categories);
});
}, 6000000000);
function setActive(category, isActive) {
categories.set(category, isActive);
}
//disable some category
setActive("sad", false);
CodePudding user response:
Make a javascript class that let's you register the category of command by sending a function (the command), a string (the category), and an interval.
myClass.register("some-category", 60000, function(){ doWork(); });
The class will need to maintain each category in a separate array. I would make an object of arrays since they can be referenced via string. E.g.
categories["some-category"].push(command);
Now that you have a registration tool and a way to store the commands sorted. Add a few methods to your javascript class for starting and stopping these:
startAll();
stopAll();
startCategory("some-category");
stopCategory("some-category");