Search code examples
javascriptperformancelivetransition

Reduce CPU usage in jQuery DOM manipulation


Is there anything I can do to this code to make it more CPU efficient (it is hitting about 80 percent of my CPU now)? I learned javascript yesterday, so it may just be that I am inexperienced. This code controls the transitions of a rather large array of tiles. On mouseover, the tiles flip over and flip back on mouseoff. There will be several threads running at once, I don't see a way around that one. I am using this script because I need to control exactly what the transitions do in ways that webkit-transitions does not support. Hopefully the comments are meaningful enough to shed some light on the code. The function is live because the array of tiles is created in javascript when the page is loaded. After that, there are no more tiles created.

The source can be found here. I don't have a working upload yet. wikisend.com/download/811662/test.zip

Thank you.

    //By default, javascript will not complete a hover transition unless the mouse 
remains over the entire duration of the transition. This scrip will force the hover 
transition to completion.
$(document).ready(function() {
    $('.tile').live('mouseenter mouseleave', (function() {

    if (event.type == 'mouseover') {
        var $this = $(this);
        $this.addClass('hover');

        //prevents mouseleave from happening when user re-enters after exiting before time is up
        $this.data('box-hover-hovered', false);
        //tile is not ready for leaving hover state
        $this.data('box-hover-not-ready', true);
        var timeout = setTimeout(function() {
            //box will be ready after time is up
            var state = $this.data('box-hover-hovered');
            if (state) { //this is entered when user exits before
                //time is up
                $this.removeClass('hover');
            }
            $this.data('box-hover-not-ready', false);
            //it's ready
        }, 400); // .1 second
        // Remove previous timeout if it exists
        clearTimeout($this.data('box-hover-timeout'));
        //stores current timer id (current timer hasn't executed yet)
        $this.data('box-hover-timeout', timeout);
    }

    else {
        var $this = $(this);

        // If not not-ready, do nothing
        // By default, the value is `undefined`, !undefined === true
        var not_ready = $this.data('box-hover-not-ready');
        if (!not_ready) {
            //if user remains hovering until time is up.
            $this.removeClass('hover');
        } else {
            //user would not have completed the action
            $this.data('box-hover-hovered', true);
        }
    }
}));
});​

Solution

  • OK, if what you want to do is to make sure that the no-hover to hover transiton completes before unhovering, you can do it like this:

    $(document).ready(function() {
        $(document.body).on('mouseenter mouseleave', '.tile', function(event) {
            var $this = $(this);
            if (event.type == 'mouseenter') {
                $this.data("hovering", true);
                if (!$this.hasClass('hover')) {
                    $this.addClass('hover');
                    var timeout = setTimeout(function() {
                        $this.removeData("timer");
                        if (!$this.data("hovering")) {
                            $this.removeClass('hover');
                        }
                    }, 400);
                    $this.data("timer", timeout);
                }
            } else {
                $this.data("hovering", false);
                // if no timer running, then just remove the class now
                // if a timer is running, then the timer firing will clear the hover
                if (!$this.data("timer")) {
                    $this.removeClass('hover');
                }
            }
        });
    });​
    

    And here's a working demo with full code comments: http://jsfiddle.net/jfriend00/rhVcp/

    This a somewhat detailed explanation of how it works:

    • First off, I switched to .on() because .live() is deprecated now for all versions of jQuery. You should replace document.body with the closest ancestor of the .tile object that is static.
    • The object keeps a .data("hovering", true/false) item that always tells us whether the mouse is over the object or not, independent of the .hover class state. This is needed when the timer fires so we know what the true state needs to be set to at that point.
    • When a mouseenter event occurs, we check to see if the hover class is already present. If so, there is nothing to do. If the hover class is not present, then we add it. Since it wasn't previously present and we just added it, this will be the start of the hover transition.
    • We set a timer for the length of the transition and we set a .data("timer", timeout) item on the object so that future code can know that a timer is already running.
    • If we get mouseleave before this timer fires, we will see that the .data("timer") exists and we will do nothing (thus allowing the transition to complete).
    • When the timer fires, we do .removeData("timer") to get rid of that marker and then we see whether we're still hovering or not with .data("hovering"). If we are no longer hovering (because mouseleave happened while the timer was running), we do .removeClass("hover") to put the object into the desired state. If we happen to be still hovering, we do nothing because we're still hovering so the object is already in the correct state.

    In a nutshell, when we start a hover, we set the hover state and start a timer. As long as that timer is running, we don't change the state of the object. When the timer fires, we set the correct state of the object (hover or no hover, depending upon where the mouse is). This guarantees that the hover state will stay on for at least the amount of time of the transition and when the min time passes (so the transition is done), we update the state of the object.

    I've very carefully not used any global variables so this can work on multiple .tile objects without any interference between them.

    In an important design point, you can never get more than one timer going because a timer is only ever set when the hover class did not exist and we are just adding it now and once the timer is running, we never remove the hover class until the timer is done. So, there's no code path to set another timer once one is running. This simplifies the logic. It also means that the timer only ever starts running from when the hover class is first applied which guarantees that we only enforce the time with the hover class from when it's first applied.

    As for performance, the CSS transition is going to take whatever CPU it takes - that's up to the browser implementation and there's nothing we can do about that. All we can do to minimize the CPU load is to make sure we're doing the minimum possible on each mouse transition in/out and avoid DOM manipulations whenever possible as they are typically the slowest types of operations. Here we're only adding the hover class when it doesn't already exist and we're only removing it when the time has expired and the mouse is no longer over it. Everything else is just .data() operations which are just javascript hash table manipulations which should be pretty fast. This should trigger browser reflow only when needed which is the best we can do.

    Selector performance should not be an issue here. This is delegated event handling and the only selector that is being checked live (at the time of the events) is .tile and that's a very simple check (just check if the event.target has that class - no other objects need to be examined. One thing that would be important to performance is to pick an ancestor as close as possible to '.tile' for the delegated event binding because this will spend less time bubbling the event before it's processed and you will not end up with a condition where there are lots of delegated events all bound to the same object which can be slow and is why .live() was deprecated.