Increase consumption and Tab Lock, with Script that draws numbers

Asked

Viewed 23 times

0

I was trying to write a script that draws 6 numbers from 1 - 60, without repetition. The Script is working, but I noticed that as I’m testing/updating the page, there comes a time when the browser increases the memory consumption and the tab stops responding. I imagine it’s a problem in the code, they could point out to me 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>
  • You are right, this code even if simple devours the processor and the memory, this is because I am using an I7 with 08 gigas of memory, caracaaaaaaassss...

1 answer

0

Make it this way that it will be faster, because it does not recreate the 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]+ ', ';
        }
};

Browser other questions tagged

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