[removed] What's more efficient, IF block or TRY/CATCH?

前端 未结 7 1265
忘了有多久
忘了有多久 2020-12-14 08:55

I\'d love some other opinions on what\'s more efficient in this code. Basically in the following code, there\'s a setInterval loop and I need 4 requirements to be true befor

7条回答
  •  旧时难觅i
    2020-12-14 09:37

    The other answers are correct, try/catch is for exceptional circumstances and error handling. if conditions are for program logic. "Which is faster?" is the wrong question.

    A good rule of thumb, if you're doing nothing with the exception, it's probably not an exception!

    To figure out which to use, let's break down your if condition.

    1. typeof jQuery == 'function' Is the jQuery() function defined?
    2. typeof nav == 'object' Does the nav global variable contain an object?
    3. typeof pageid != 'undefined' Is the pageid global variable defined?
    4. typeof document.getElementById('leftnav') == 'object' Does the document contain a leftnav element?

    The first is clearly an exception. You ain't getting far without a jQuery() function.

    The second is also an exception. You're not going anywhere without a nav object.

    The third is an exception. You need a pageid to do anything.

    The fourth is probably logic. "Only run this code if there is a leftnav element". It's hard to tell because the rest of the code doesn't reference a leftnav element! Only the comments do, a red flag. So it's probably a programming mistake.

    So I'd probably do this (with apologies if I'm butchering jQuery):

    var intvar = setInterval(function() {
        // If there's no leftnav element, don't do anything.
        if( typeof document.getElementById('leftnav') != 'object') {
            return;
        }
    
        try {
            clearInterval(intvar);
            jQuery('#'+nav[pageid].t1+'>a')
                .replaceWith(jQuery(''+jQuery('#'+nav[pageid].t1+'>a').text()+''));
    
            //set display classes for nav
            jQuery('#'+nav[pageid].t1)
                .addClass('selected')
                .find('#'+nav[pageid].t2)
                .addClass('subselect');     //topnav
            jQuery('#'+nav[pageid].t3)
                .addClass('selected')
                .find('#'+nav[pageid].t4)
                .addClass('subselect');     //leftnav
        }
        catch(err) {
            ...do something with the error...
        }
    },100);
    

    ...but I'd really examine if the leftnav element check is applicable.

    Finally, I can't help but comment that this "function" is working with global variables. You should instead be passing nav and pageid into the function in order to maintain encapsulation and your sanity.

提交回复
热议问题