how to make the interval value dynamic and random every loop of setInterval NodeJs

how to make the interval value dynamic and random every loop of setInterval NodeJs

Problem Description:

I have a function that generates a random number from 3 to 5 (including 3 and 5) and I want the setInterval that triggers a function in nodeJS in loop to have its interval value received from another function and that each time the loop occurs in setInterval the value is different (random).

bot.start(async (ctx, next) => {

    ctx.reply(`Se preparem para os sinais! proximo sinal em alguns minutos`)

    if ( paused == false) {
        setInterval(() => {
            bot.telegram.sendMessage(process.env.TELEGRAM_CHANNEL, '🛑 APOSTE AGORA 🛑nn* Analisar as rodadas anteriores pra saber se vai entrar 10 segundos antes ou 10 segundos depois. *nnSaque automático 1.5x nnMax 2xnn50% de saque ativado em 1.3xnn*Gerenciamento de banca, se perder a culpa não é minha!*nnVamos pra cima voadoresnn🚀💜✅n'
            );
        }, getRandomInterval(3,5) * 1000);
    }
    next();
})
function getRandomInterval(min, max) {
    let randomInterval = Math.floor(Math.random() * (max - min) + min);
    console.log('linha 92: ' + randomInterval)
    return randomInterval;
}

Solution – 1

setTimeout is the perfect candidate for this.

bot.start(async(ctx, next) => {

  ctx.reply(`Se preparem para os sinais! proximo sinal em alguns minutos`)

  if (paused == false) {
    function foo_interval_action() {
      bot.telegram.sendMessage(process.env.TELEGRAM_CHANNEL, '🛑 APOSTE AGORA 🛑');
      setTimeout(foo_interval_action,  getRandomInterval(3, 5) * 1000);
    }
    setTimeout(foo_interval_action,  getRandomInterval(3, 5) * 1000);
  }
  next();
})

function getRandomInterval(min, max) {
  let randomInterval = Math.floor(Math.random() * (max - min) + min);
  // console.log('linha 92: ' + randomInterval)
  return randomInterval;
}

Here’s a generic function to generate variable delay interval. Nothing fancy.

function setVariableInterval(foo_do_action, foo_get_delay) {

  function do_it() {
    foo_do_action();
    setTimeout(do_it, foo_get_delay())
  }

  // right away
  do_it()
}


var foo_get_delay = function() {
  return Math.random() * 3000 + 250
}

var foo_do_action = function() {
  console.log("time now is: " + new Date())
}

setVariableInterval(foo_do_action, foo_get_delay)
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject