Vinyl Windows
Vinyl Windows

Reputation: 503

jQuery is locking up browser

I am not sure if I should be clearing everything or resetting something somewhere.

What is happening is that the browser will lock up for 10 - 30 seconds when setting a int value in the input textbox.

Here is a little snippet:

function RunIt() {
    $('#txTotW').bind('keyup', function () { 
        _totWidth = parseInt($(this).val()); 
        $('#totalWidth').text($(this).val()); 
        RunIt(); 
    });
    $('#txTotH').bind('keyup', function () { 
        _totHeight = parseInt($(this).val()); 
        RunIt(); 
    });
    $('#txBayCnt').bind('keyup', function () { 
        _bayCount = parseInt($(this).val()); 
        RunIt(); 
    });
}

If at any time one of the keyup events are fires I rebuild a table by .find('tr').remove() and this table only has three rows max at any time, but since the change of one value the entire table will be rebuilt.

This does not seem like a big enough load to make the browser lock up.

What can I do to fix this?

Upvotes: 0

Views: 285

Answers (2)

deltree
deltree

Reputation: 3824

You call RunIt() inside each of your callbacks. This is recursive,and you are ending up in a loop that exponentially increases the number of calls. A simple solution would be to add parameters to RunIt() so that you are only assigning these callbacks to the relevant rows.

For clarification, yes, it is only binding RunIt() to each call. However, each time you call the same function, it is re-binding. By re-binding, you're causing it to duplicate the callback functions for existing rows (you get multiple callbacks per row, instead of the single callback you're going for). So in this case (3 methods), each method gets bound, then all 3 methods are called, and you end up with 1 + 2 + 3 calls which totals 6 more bindings, so the next time it's called it's 6 + 7 + 8 calls which adds a much larger number of bindings and continues to grow as you add rows until it is nearly unmanageable, as you've experienced.

Upvotes: 0

btown
btown

Reputation: 2281

When you bind a function to an event in jQuery, it is permanently stored in a data structure as behavior that will always happen when that event is called (unless you explicitly remove the binding). So when you call RunIt() from within those callbacks/handlers, you're adding redundant functions to that structure. The reason this slows things down is that the number of redundant callbacks increases exponentially: first 1 on each event, then 2, then 4, then 8, and so on. You don't need to call RunIt() from within those callbacks at all: the bindings will still be there.

Upvotes: 1

Related Questions