1

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);
        }
    }
}));
});​
Chet
  • 1,209
  • 1
  • 11
  • 29
  • do you have a demo page for this? – Joseph Mar 18 '12 at 06:05
  • If all you're trying to do with this is make sure that the `hover` class stays applied to an object for at least 400ms after the object is first hovered, then there are vastly simpler ways to do this that would use a lot less CPU. But, before writing up such an answer, can you confirm that that's all you're trying to accomplish with this code? – jfriend00 Mar 18 '12 at 06:46
  • All that matters to me is that the no-hover to hover transition always completes even if the user moves the mouse away in the first 400ms. The hover to no-hover state is reversible and follows the default behavior of transitions. So yes, what you are talking about sounds correct. – Chet Mar 18 '12 at 06:59
  • OK, I wrote an answer that does what you asked for. Though I did not look at your implementation when I wrote mine (I just went from the desired goal), my implementation is similar to yours, but simpler in a couple ways. – jfriend00 Mar 18 '12 at 09:47

2 Answers2

3

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • First off, thanks for taking the time to code that up. I swapped out your code for mine, and it still works properly. The CPU is still massive, this led me to try something dirt simple to test where the work is actually being done. It no longer serves my purpose, but the CPU on that is even super high. I believe the CSS is the problem. I am only looking at the %CPU in my activity monitor (on osx lion) and it will jump to the mid 90's pretty quickly. This seems unacceptably high for CSS alone, do you agree? – Chet Mar 18 '12 at 13:38
  • I guess the CSS bit does answer the question. It's a shame that I can't cut it down further (that I know of) without cutting back on CSS. – Chet Mar 18 '12 at 22:58
  • @Chet - I can't seem to access [your test page](http://www.chetgnegy.com/test/index.html) now. There may be ways to simplify to make the CSS faster without changing the visuals. – jfriend00 Mar 18 '12 at 23:41
  • I know it works for me on chrome. A friend on another computer just verified that it works on safari. What browser are you running? I'm not making guarantees about any others. – Chet Mar 19 '12 at 03:16
  • It's working now. I couldn't even reach the page on the internet earlier. I think your best bet is to find a non-3D transition that looks good to you. As it is, you're doing a very complicated way of just getting the edges to animate into the middle. I'd bet you that you could find a non-3D transition that would look similar, but use a lot less CPU. – jfriend00 Mar 19 '12 at 03:31
1

Edit: See dbaupp's comment below.

Right off the bat I'd say use a more specific selector instead of just $('.tile'). This simply means change your selector to something like $('div.tile') or better yet $('#someparentid div.tile') instead.

This way you won't have to traverse the entire DOM searching for a matching class.

I'm afraid Mikko appears to be quite right http://jsperf.com/jquery-right-to-left-selectors

Apparently my solution was an old misconception. Good ways to improve jQuery selector performance?

The only way to speed up that selector is to call it by id (e.g., $('#tile')), which unfortunately doesn't seem like a solution that would work for you given that you likely have multiple tile elements.

Community
  • 1
  • 1
Dennis Plucinik
  • 224
  • 3
  • 8
  • CSS selectors are evaluated from right to left and your examples actually slow down the code. – Mikko Ohtamaa Mar 18 '12 at 06:24
  • 1
    Facts about CSS performance http://perfectionkills.com/profiling-css-for-fun-and-profit-optimization-notes/ – Mikko Ohtamaa Mar 18 '12 at 06:28
  • jQuery will fall back to native querySelectorAll() when possible and thus the same implications apply for jQuery – Mikko Ohtamaa Mar 18 '12 at 06:28
  • 1
    If you cache the context, i.e. `var context = $("#someparent"); $(".tile", context);`, then you get better performance than just `$(".tile")`: http://jsperf.com/jquery-right-to-left-selectors/2 – huon Mar 18 '12 at 08:33