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

  • Home
  • SEARCH
  • 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 367945
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T13:46:36+00:00 2026-05-12T13:46:36+00:00

After becoming slightly uncomfortable with multiple calls to the same function, with different parameters

  • 0

After becoming slightly uncomfortable with multiple calls to the same function, with different parameters (as shown in the dom ready section of the code below), I decided to test out passing the parameters for this function by iterating through an array instead (as shown in mouse_function_two). To my surprise I found that mouse_function_two ran considerably faster.

My question is, would mouse_function_two be considered better JavaScript practice than mouse_function_one?

Note: I am slightly concerned I may not be using firebugs console.time utility correctly!

Initial attempt

function mouse_function_one (hover_selector, class_name, add_link) {

  hover_item = $(hover_selector)

  hover_item.each(function(){
    $(this).hover(
      function () {
        $(this).addClass(class_name);
        if ( add_link == true ) {
          $(this).click(function(){
            var href = $(this).find('a').attr('href');
            window.location.href = href;
          });

        }
        else return false;
      },
      function () {
        $(this).removeClass(class_name);
    });
  });
}

Second (faster) attempt:

function mouse_function_two (args) {

  for (var i=0; i < args.length; i++) {

    hover_selector = $(args[i][0]);
    class_name = args[i][1];
    add_link = args[i][2];

    hover_item = $(hover_selector)

    hover_selector.each(function(){
      $(this).hover(
        function () {
          $(this).addClass(class_name);
          if ( add_link == true ) {
            $(this).click(function(){
              var href = $(this).find('a').attr('href');
              window.location.href = href;
            });

          }
          else return false;
        },
        function () {
          $(this).removeClass(class_name);
        });
    });

  }
}

Client code:

// on dom ready
$(function(){

  console.time('f1');
  mouse_function_one('#newsletter .right', 'hovered', true);
  mouse_function_one('.block-couple div.right', 'hovered', false);
  mouse_function_one('.bulletin', 'selected', true);
  console.timeEnd('f1'); //speed is calculated as 104ms

  args = [];
  args[0] = ['#newsletter .right', 'hovered', true]; 
  args[1] = ['.block-couple div.right', 'hovered', false]; 
  args[2] = ['.bulletin', 'selected', true]; 

  console.time('f2');
  mouse_function_two(args);
  console.timeEnd('f2'); //speed is calculated as 10ms

});
  • 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-12T13:46:37+00:00Added an answer on May 12, 2026 at 1:46 pm

    If the second routine is faster, it’s probably because it doesn’t do what it is supposed to do. Have a look at this snippet:

      for (var i=0; i < args.length; i++) {
    
        hover_selector = $(args[i][0]);
        class_name = args[i][1];
        add_link = args[i][2];
    
        hover_item = $(hover_selector)
    
        hover_selector.each(function(){
          $(this).hover(
            function () {
    

    Two problems here:

    1. You’re using implicit global variables.
    2. Blocks in JavaScript do not introduce a new scope.

    Either of these would cause the same bug, together they just make it doubly certain that it will occur: the closures created for the hover() event handler functions contain only the values of the final loop iteration. When these handlers are finally called, class_name will always be "selected", and add_link will always be true. In contrast, your original function would be called with a different set of parameters each time, which would be captured in the function’s scope by the event handlers, and consequently work as expected.


    As for the style… It’s messy. You’ve encased the entire function body in a loop, removed descriptive arguments, and greatly complicating the calling of the function.

    Fortunately, you can address the issue I point out above, simplify the function, and simplify how it is called all in one go:

    // For starters, I've eliminated explicit parameters completely.
    // args wasn't descriptive, and all JavaScript functions have an implicit
    // arguments array already - so let's just use that.
    function mouse_function_three () {
    
      // use jQuery's array iteration routine:
      // this takes a function as an argument, thereby introducing scope and
      // avoiding the problem identified previously
      $.each(arguments, function() {
        var class_name = this.class_name;
        var add_link = this.add_link;
        var selected = $(this.hover_selector);
    
        // no need to use selected.each() - jQuery event binding routines
        // always bind to all selected elements
        selected.hover(function() {
          $(this).addClass(class_name);
        },
        function() {
          $(this).removeClass(class_name);
        });
    
        // bring this out of the hover handler to avoid re-binding
        if ( add_link ) {
          $(selected).click(function(){
            var href = $(this).find('a').attr('href');
            window.location.href = href;
          });
    
        }
      }); // each set of arguments
    }
    

    You’d then call this new routine like so:

    console.time('f3');
    mouse_function_three( 
     {hover_selector: '#newsletter .right', class_name: 'hovered', add_link: true},
     {hover_selector: '.block-couple div.right', class_name: 'hovered', add_link: false},
     {hover_selector: '.bulletin', class_name: 'selected', add_link: true}
    );
    console.timeEnd('f3');
    

    Note that these changes may very well eliminate any speed difference from your initial attempt, as the code effectively does the very same thing, but with the additional step of packing and then extracting parameters…

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

Sidebar

Ask A Question

Stats

  • Questions 168k
  • Answers 168k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Do yourself a favour, and use one of the many… May 12, 2026 at 1:46 pm
  • Editorial Team
    Editorial Team added an answer If the regular expression implementation supports look-around assertions, try this:… May 12, 2026 at 1:46 pm
  • Editorial Team
    Editorial Team added an answer Have you had a look at the Bulk Insert tsql… May 12, 2026 at 1:46 pm

Related Questions

I'm developing a LoB application in Java after a long absence from the platform
After becoming somewhat estranged open source, and spending some years developing web applications in
We have started using Spring framework in my project. After becoming acquainted with the
I installed Subversion 1.5.x and then TortoiseSVN 1.6.x. All was fine using the 1.5.x
I am using the UIImagePickerController in order to let the user select an image

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.