0

I have this code cycling through my page, and it causes a slight page lag when a select box is checked. Is there any way to optimize the code? I am still very new to javascript so its possible that I mixed a few things up.

var OpeningEmployees = document.getElementById('opener');
var QuantityDDOptions = jQuery('#opener option').length;

var DropDownNames = new Array();
DropDownNames[0] = "opener";
DropDownNames[1] = "mid";
DropDownNames[2] = "closer";
DropDownNames[3] = "SRTW";
DropDownNames[4] = "CR";
DropDownNames[5] = "Aisles";
DropDownNames[6] = "BD";
DropDownNames[7] = "Fridge";
DropDownNames[8] = "AP";
DropDownNames[9] = "EPV";



OpeningEmployees.onchange = function () {
    var openerVals = $("#opener").val();
    for (var j = 1; j < DropDownNames.length; j++){
        for (var x = 0; x < QuantityDDOptions; x++) {
            var EmployeelNumLine = document.getElementById(DropDownNames[j]).options[x].value;
            if (openerVals == null){
                jQuery("select#"+DropDownNames[j]+" option")[x].removeAttribute("disabled");
                $("#"+DropDownNames[j]).multiselect("refresh");
            } else if(openerVals.indexOf(EmployeelNumLine) > -1) {
                jQuery("select#"+DropDownNames[j]+" option")[x]['disabled'] = "true";
                $("#"+DropDownNames[j]).multiselect("refresh");
            } else if(!openerVals.indexOf(EmployeelNumLine) > -1){
                jQuery("select#"+DropDownNames[j]+" option")[x].removeAttribute("disabled");
                $("#"+DropDownNames[j]).multiselect("refresh");
            }
        }
    }
}
2
  • 1
    There seems to be some code missing. You need to explain what you are trying to do and what the code actually does.
    – RobG
    Mar 22, 2013 at 2:15
  • 2
    codereview.stackexchange.com
    – j08691
    Mar 22, 2013 at 2:22

1 Answer 1

1

In general, if your loop is locking up the thread, you can refactor it as a recursive loop that is invoked using timeouts. That prevents the UI from freezing up.

For large values of n, this will freeze your browser:

for (i = 0; i < n; i++){
    //dosomething();
}

This on the other hand, slows you down, but doesn't lock up the browser:

(function iterate(i) {
    if (i < n) {
        //dosomething();

        setTimeout(function () {
            iterate(++i);
        }, 0);
    }
})(0)
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.