Stop a setInterval () in JavaScript

2

I am developing a number increase with setInterval (), and I want the setInterval to stop when the counter reaches a certain number.

var cont = 0;
var rango = document.getElementById('rango');

    var id = setInterval(function(){
        rango.innerHTML = cont;
        cont++;
    }, 1000);   

    if(cont == 10) 
    {
        clearInterval(id);
    }

The problem is that to carry out the conditional the variable cont must be in the same scope, but it is not since it is inside the function setInterval. What I do is take it out and put it outside.

var id = setInterval(function(){
            rango.innerHTML = cont;
         }, 1000);  
         cont++;

         if(cont == 10) {
            clearInterval(id);
         }

but when doing this, being outside the setInterval does not increase. Who knows how to locate the code? Who explains to me? who can help me? thanks in advance

    
asked by Odannys De La Cruz 07.10.2017 в 00:22
source

2 answers

4

The first thing is that your first code is correct. cont must be initialized out of the range and should be increasing within it. Now what does not work is the condition, it must stay within the interval, otherwise it will only be done once and the interval will continue until the end of time. I leave the snippet with the necessary corrections to work according to what you occupy.

var cont = 0;
var rango = document.getElementById('cont');

    var id = setInterval(function(){
        rango.innerHTML = cont;
        cont++;
        if(cont == 10) 
        {
            clearInterval(id);
        }
    }, 1000); 
<span id='cont'></span>
    
answered by 07.10.2017 / 00:32
source
-1

Maybe you can replace the setInterval with a function, here's the code:

//Variable global
var cont = 0,
       rango = document.getElementById('rango');

//Definimos una función recursiva
function interval(){
    rango.innerHTML = cont;
    cont++;
    if(cont != 10){
        interval();
    }
}

The only thing left is to call the function:     interval ();

    
answered by 07.10.2017 в 00:59