SetInterval and restart

1

I have setInterval with an interval of 2 seconds. I need to stop this interval at a certain point and start it again with a new time.

Scope
I make an AJAX inside the setInterval. As soon as the AJAX response is success (for example), it repeats the interval again. If it is an error, it stops the interval, changes the interval time, and restarts it again.

I've been able to do the following so far:

var TempoRequest = 2200;
var Ativo = true;
if(Ativo === true){
    VerificaChat = setInterval( function(){
        if(acao){

        //repete o intervalo dnv

        }else{
            var Ativo = false;
            var TempoRequest = 15000;
            clearInterval(VerificaChat);
        }

    }, TempoRequest );
}
    
asked by anonymous 22.06.2018 / 19:51

1 answer

2

I've done something very simple here, see if it helps.

  tempo = 2000; //crio variável global para controlar o tempo,
  number = 1; //essa variavel e apenas pra imprimir e controlar o incremento, mas no seu caso vai ser controlado pelo sucesso do AJAX

  setInterval(function(){
    if (number>0 && number<5) {
      document.write(number);
      number++;
    }else{
      document.write("-")
      number = 1;
      tempo += 100; //nessa parte eu apenas incrementei o tempo da variavel, mas se vc quiser pode resetar ela ou criar modo dinâmico para setar um tempo.
    }
  },tempo);
    
22.06.2018 / 23:01