Search code examples
javascriptjqueryperformancepagespeed

Faster javascript processing


Just asked my first question and got a great response. So helpful. Helped me create this bit of javascript to create two random numbers on the same page.

<script>
window.onload = function(){
generateRandomNumber1();
generateRandomNumber2();
}</script>

<script>
function generateRandomNumber1(){
var n = 30;
var number = Math.floor(Math.random()*n)+1;
document.getElementById("random1").innerHTML = number;
}

function generateRandomNumber2(){
var n = 15;
var number = Math.floor(Math.random()*n)+1;
document.getElementById("random2").innerHTML = number;
}
</script>

A also use this bit of script to show the two divs on a time delay:

<script>
var toggle = function() {
$("#loadingContainer1").show();
}
setTimeout(toggle, 1000);
</script>
<script>
var toggle = function() {
$("#loadingContainer1").hide();
}
setTimeout(toggle, 8000);
</script> 
<script>
var toggle = function() {
$("#loadingContainer2").show();
}
setTimeout(toggle, 7000);
</script> 
<script>
var toggle = function() {
$("#loadingContainer2").hide();
}
setTimeout(toggle, 14000);
</script> 

Really cumbersome, I know, but it works, and I'm quite pleased with myself for working most of this out myself (with a lot of help from other people's threads on Stack Overflow).

Anyway, it all works, so that isn't my issue, the only problem is, that the random number generator works so slowly, that the divs the numbers appear in have usually come and gone before the random numbers are generated. After I refresh the page a couple of times, they normally start working a bit faster, but is there any way I could speed up the process so the random numbers are generated within the first second of the page loading.

Thanks very much.


Solution

  • There is a LOT of messy code there, but maybe it's because onload doesn't fire until the page has completely loaded that it's slow. Here's a rewrite of your code to work better:

    <script type="text/javascript">
        $(function() { // uses jQuery's "ready" handler
            $("#random1").html(Math.floor(Math.random()*30)+1);
            $("#random2").html(Math.floor(Math.random()*15)+1);
            $("#loadingContainer1").delay(1000).fadeIn(0).delay(7000).fadeOut(0);
            $("#loadingContainer2").delay(7000).fadeIn(0).delay(7000).fadeOut(0);
        });
    </script>
    

    Hope this helps!