How to generate number without repetition with a pause button?

1

I would like to have a button with the function of PAUSE , and delete duplicate numbers.

A counter below that when I press PAUSE it displays the number of the result with the TOTAL of generated lines.

function append(el) {
    //eu coloco os 16 primeiro digitos aqui, e ele gera mais 4 aleatorio
    var txt = "1212" + "9057" + "9240" + "8105";
    var x = Math.floor((Math.random() * 9000) + 1000);
    document.getElementById(el).innerHTML += txt + x + "<br>";
    //tempo de gerar numeros 1s
    setTimeout(function() {
        append("timeout");
    }, 1000);
    //AQUI EU QUERO UM FILTRA PARA NAO DUPLICAR
    // E UM BOTAO DE PAUSE E UM TXT COM TOTAL DE LINHAS GERADAS

}


append("timeout");
<p>GERADOR DE NUMEROS SEM REPETIÇAO E COM BOTAO DE PAUSE</p>
<hr>
<button name="pause" id="pause">PAUSE</button>
<div id="timeout"></div>
<div id="interval"></div>
    
asked by anonymous 20.04.2017 / 11:59

2 answers

0

The setInterval Returns an interval ID, and can be passed as parameter in function clearInterval() , if you want to stop it.

See it working:

var stop;
var contador = 0;
function append(el) {
    contador++;
    var txt = "1212" + "9057" + "9240" + "8105";
    var x = Math.floor((Math.random() * 9000) + 1000);
    document.getElementById(el).innerHTML += txt + x + "<br>";

    stop = setTimeout(function() {
        append("timeout");
    }, 1000);


}
function pause(){
   document.getElementById('totalItens').innerHTML = 'Total de Itens:' + contador;
   clearInterval(stop);
}
append("timeout");
<p>GERADOR DE NUMEROS SEM REPETIÇAO E COM BOTAO DE PAUSE</p>
<hr>
<button name="pause" id="pause" onclick='pause()'>PAUSE</button>
<div id="timeout"></div>
<div id="interval"></div>
<div id="totalItens"></div>
    
20.04.2017 / 14:53
1

What I would do is the following:

First use setInterval instead of setTimeout:

var myVar = setInterval(function(){ gerarNumero() }, 1000);

When you want to stop, use clearInterval:

clearInterval(myVar);

Since the duplication case is more difficult, I recommend making an array and putting each generated number on it, and then check if the new number is in the array, if it is not, return the number if you run the function again. .

var numeros = [];

function gerarNumero(){    
    var x = Math.floor((Math.random() * 9000) + 1000);
    var existe = false;
    for(var i in numeros){
        if(numeros[i] == x) existe = true;
        break;
    }    
    if(!existe){
        numeros.push(x);
        document.getElementById(el).innerHTML += txt + x + "<br>";
    }else{
        gerarNumero();
    }
}

I did not test the code, but it will be something along those lines ...

I hope it helps ...

    
20.04.2017 / 12:43