Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7659857
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T13:23:17+00:00 2026-05-31T13:23:17+00:00

Is there anything I can do to this code to make it more CPU

  • 0

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);
        }
    }
}));
});​
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T13:23:17+00:00Added an answer on May 31, 2026 at 1:23 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Can you simplify this code?. Is there anything we can do to make it
There maybe some simlar questions to this but I can't see anything that really
Is there anything I can do while coding in Asp.net to make my website
Can anyone suggest tips or alterations to make this code cleaner and faster? This
Is there anything which can help with msmq monitoring? I'd like to get some
Is there anything simple Java can't do that can be done in a similar
Is there anything built into the core C# libraries that can give me an
I'm using System.Drawing.Color, is there anything in Visual Studio that can display the color
Is there a specific protocol used for network discovery? I'm looking to code this
Is there anything like ELMAH for Windows Forms? I'm looking for a standard way

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.