Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping the Function cause it unresponsive in javascript

Here is the code that i tried for snow flakes. Everything seems ok but once the certain period of time that script get unresponsive means (It slow down the browser firefox). I am not sure why this should happen. How can i make it as responsive without cause anything to browser. Here is FIDDLE

How can i make it responsive script which doesn't cause any.! I think I made a mistake in looping the javascript function :( Any Suggestion Would Be great.

Thanks

Javascript:

// window.setInterval(generateSnow, 0);
var windowHeight = jQuery(document).height();
var windowWidth = jQuery(window).width();
function generateSnow() {
    for (i = 0; i < 4; i++) {
        var snowTop = Math.floor(Math.random() * (windowHeight));
        snowTop = 0;

        var snowLeft = Math.floor(Math.random() * (windowWidth - 2));
        var imageSize = Math.floor(Math.random() * 20);

        jQuery('body').append(
            jQuery('<div />')
                .addClass('snow')
                .css('top', snowTop)
                .css('left', snowLeft)
                .css('position', 'absolute')
                .html('*')
        );
    }
}


function snowFalling() {
    jQuery('.snow').each(function(key, value) {
        if (parseInt(jQuery(this).css('top')) > windowHeight - 80) {
            jQuery(this).remove();
        }
        var fallingSpeed = Math.floor(Math.random() * 5 + 1);
        var movingDirection = Math.floor(Math.random() * 2);
        var currentTop = parseInt(jQuery(this).css('top'));
        var currentLeft = parseInt(jQuery(this).css('left'));
        jQuery(this).css('top', currentTop + fallingSpeed);
        if (movingDirection === 0) {
            jQuery(this).css('bottom', currentLeft + fallingSpeed);
        } else {
            jQuery(this).css('bottom', currentLeft + -(fallingSpeed));
        }
    });
}

window.setInterval(snowFalling, 15);
window.setInterval(generateSnow, 1000);
like image 467
Vignesh Pichamani Avatar asked Oct 11 '13 13:10

Vignesh Pichamani


People also ask

How to stop the loop in JavaScript?

The break statement breaks out of a switch or a loop. In a switch, it breaks out of the switch block. This stops the execution of more code inside the switch. In in a loop, it breaks out of the loop and continues executing the code after the loop (if any).

Can you break out of a for loop JavaScript?

You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.

How to break JavaScript code?

The break statement is used to terminate the loop immediately when it is encountered. The syntax of the break statement is: break [label];


2 Answers

You're adding and removing lots of elements on the page during runtime, making browsers refresh the structure of that page frequently.

That approach is:

  1. the worst thing you can do performance-wise
  2. probably making the browser fall to its knees once enough DIVs have been generated, removed, generated, removed, generated, removed......

A mobile browser would probably just freeze after 2 seconds with this config.

I recommend pre-generating all DIVs right at the beginning, re-using them and using CSS animations or jQuery animate() to accomplish what you're trying to do.

like image 195
Zathrus Writer Avatar answered Oct 22 '22 17:10

Zathrus Writer


As @ZathrusWriter mentioned, you should re-use your snowflake elements so memory does not bloat.

The reason the browser starts to get slow after creating a bunch of snowflakes is because JavaScript manages memory using a garbage collector. Thus the memory is getting freed much slower than you're allocating memory for new snowflakes. Ideally, you want to allocate memory for all the snowflakes once.

Basically, create the elements for the number of snowflakes you want on screen at any given time. Place them all on the screen in random locations to start. Then once a snowflake goes off-screen or invisible, that snowflake is usable again. So you'll move it back to the top (possibly in another random location) and make it fall like a snowflake again (instead of deleting it and creating a new one).

This is one step away from creating a particle emitter.

like image 39
jsea Avatar answered Oct 22 '22 16:10

jsea