Increased consumption and Aba Lock, with Script that draws numbers

0

I was trying to make a script that draws 6 numbers from 1 - 60, without repetition. The Script is working, but I noticed that as I test / refresh the page, there comes a time when the browser increases memory consumption and the tab stops responding. I imagine it's a problem in the code, could you point out the error?

    <script>
        var numerosSorteados = function(){
            var num = []; 
            var numero;
            var chave = true;
            var i = 0;
            while( i < 6){
                numero = Math.round((Math.random() * 60) + 1);

                for(var j = 0; j < i; j++){
                    if(numero == num[j]){
                        chave = false;
                        break;
                    }
                }
                if(chave){
                    num.push(numero);
                    i++;
                    }
                    document.write(numero+"</br>");
                    chave == true;
            }
            return num;
        }
        document.write(numerosSorteados());
    </script>
    
asked by anonymous 23.10.2015 / 17:55

1 answer

0

Make this way faster because it does not recreate array .

    var numerosSorteados = function(){
        var maximo = 60;
        var resultados = 6;

        var i, arr = [];
        for (i = 0; i < maximo; i++) {
            arr[i] = i + 1;
        }

        var p, n, tmp;
        for (p = arr.length; p;) {
            n = Math.random() * p-- | 0;
            tmp = arr[n];
            arr[n] = arr[p];
            arr[p] = tmp;
        }

        for (var i = 0; i < resultados; i++) {
            document.getElementById('out').innerHTML +=  arr[i]+ ', ';
        }
};
    
23.10.2015 / 18:25