Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

129
Vistas
How do I run multiple setIntervals efficiently?

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.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

What about something like this?

const myThings = ['thing1', 'thing2', 'thing3'];

function runThings(things, msBetweenThings) {
  let nextThingIndex = 0;
  console.log('running things');
  const myInterval = setInterval(() => {
    if (nextThingIndex >= 0) {
      console.log(things[nextThingIndex++]);
      if (nextThingIndex >= myThings.length) {
        console.log('ran out of things!')
        clearInterval(myInterval);  // cleanup when done
      }
    }
  }, msBetweenThings);
}
// start it up by sending a list of things and a delay
runThings(myThings, 10000)

about 4 years ago · Juan Pablo Isaza Denunciar

0

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);

about 4 years ago · Juan Pablo Isaza Denunciar

0

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");

Here is an example registration method:

function register(category, interval, callback) {
    if(!this.categories[category]) this.categories[category] = [];
    let token = setInterval(callback, interval);
    this.categories[category].push({token:token, callback:callback});
}

Here is an example stopCategory method:

function stopCategory(category) {
    if(this.categories[category]) {
       for(let i=0; i<this.categories[category].length; i++) {
          clearInterval(this.categories[category][i].token);
       }
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda