Pause count - setInterval

2

I'm creating a function to start a count and when it reaches the final value it stops.

But clearInterval is not working: '(

Has anyone ever had to do something similar?

function numerosHome(){
        var inicial = 0;
        var location = document.getElementById('participantes');
        setInterval(() => {
            location.innerHTML = inicial;
            inicial++;
            if(inicial == 10){
                clearInterval();
            }
        },100);
    }
    numerosHome()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script><divclass="numeros" id="participantes">			
</div>
    
asked by anonymous 22.12.2017 / 13:13

2 answers

1

function numerosHome(){
        var inicial = 0;
        var location = document.getElementById('participantes');
        var contador = setInterval(() => {
            location.innerHTML = inicial;
            inicial++;
            if(inicial == 11){
                clearInterval(contador);
            }
        },100);
    }
    numerosHome()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script><divclass="numeros" id="participantes">			
</div>
    
22.12.2017 / 13:32
0

The syntax of the clearInterval is:

scope.clearInterval(intervalID)
  

The identifier of the replay action that you want to cancel. This ID   was returned by the call corresponding to setInterval ()

As an example, passing the value to the argument will solve: clearInterval(1)

Solution

function numerosHome() {
  var inicial = 0;
  var location = document.getElementById('participantes');
  (function() {
    let id = setInterval(() => {
      location.innerHTML = inicial;
      inicial++;
      if (inicial == 10) {
        clearInterval(id);
      }
    }, 100);
  })();
}

numerosHome();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script><divclass="numeros" id="participantes">
</div>
    
22.12.2017 / 13:17