MaiaVictor
MaiaVictor

Reputation: 52987

Could iterating through every DOM element 40 times a second cause performance issues on slower computers?

setInterval(function(){
    $("*").each(function(obj){
        if ($(this).data("x"))
            $(this).css({left:$(this).data("x")()});
        //... more code for y, w, h, x2, y2, etc...
    }
},25);

It runs perfectly on my computer - my worry is: if left this way without optimizations, could this code cause significant performance drops for users with worse computers, as it's iterating through every DOM element 40 times a second? Or is that acceptable?

Note: The point is to make it easier to create a function that will coordinate an object's position, for example: $(myObj).data("x",function(){ return sin(Date.now()/1000)*50; }) should make an object wiggle.

Upvotes: 1

Views: 83

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

It could definitely impact on performance, and especially if you have many, many elements. 40 times a second too? That seems like a lot. I'm not sure how much faster using a selector would be either because that too could be expensive.

Perhaps try $("[data-x]") as your selector instead, or use a more specific parent selector: $("#container").find('[data-x]')

Upvotes: 2

Related Questions