Pause counting - setInterval

Asked

Viewed 608 times

0

I am creating a function to start a count and when it reaches the final stop value. However the clearInterval is not working.

Has anyone ever had to do anything like this?

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>
<div class="numeros" id="participantes">
</div>

2 answers

0

The syntax of clearInterval is:

scope.clearInterval(intervalID)

The repeating action identifier you want to cancel. This ID was returned by the call corresponding to the 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>
<div class="numeros" id="participantes">
</div>

0

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>
<div class="numeros" id="participantes">			
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.