Does javascript execution stop when an invalid line is encountered?

后端 未结 4 2165
孤独总比滥情好
孤独总比滥情好 2021-02-07 05:33

If the browser is executing JavaScript on a web page and it encounters invalid JavaScript (e.g. somerandomthingy;) Does execution of JavaScript stop at that point, or do async o

相关标签:
4条回答
  • 2021-02-07 06:22

    No code is executed past the error.

    function inAFunction(){
     alert("one");
     x = y;
     alert("two");  
    }
    inAFunction();
    

    you will see "one" but not "two"

    alert("one");
    x = y;
    alert("two");
    

    you will see "one" but not "two"

    var a = {
        b : c
    }
    alert("here");
    

    you will see nothing.

    0 讨论(0)
  • 2021-02-07 06:30

    It does somewhat depend on what you're doing. Usually things will stop executing and, if you're using a smart browser with a console, an error message will be logged (and sometimes these error messages are helpful, even, but not always).

    UNCAUGHT EXCEPTION: SYNTAX ERROR, UNRECOGNIZED EXPRESSION: #

    enter image description here

    Sometimes, however, stuff will just silently fail with no error or warning, especially if you're using jQuery or another library. I've spent hours troubleshooting why something worked fine in WebKit and Firefox but silently failed in IE, and traced the culprit to a PEBCAK bug in a jQuery .append() method that was trying to insert some invalid HTML into the DOM. It was maddening because everything else worked fine, no errors, no warnings, nothing, but in IE that one function just wouldn't "go."

    0 讨论(0)
  • 2021-02-07 06:30

    Yes, except asynchronous ones. http://jsfiddle.net/pimvdb/R4dfJ/3/

    DIY:

    var a = 1, b, c;
    
    setTimeout(function() {
        b = 2;
        console.log('Running', a, b, c);
    }, 1000);
    
    somerandomthingy;
    
    c = 3;
    

    Uncaught ReferenceError: somerandomthingy is not defined

    Running 1 2 undefined

    So:

    • a and b have been set
    • c has not been set
    • Timeout still occurs

    As for 'does onclick still work' - well, if the handler is set in code that runs (i.e. before an error) it does; in case it is put after error code it won't bind the handler so events won't work.

    0 讨论(0)
  • 2021-02-07 06:33

    I think execution stops. If you set an alert after a line of code that breaks, you will not reach the alert, which leads me to believe that execution stops. I'm not sure if the same is true of asynch XmlHtttpRequests, though.

    0 讨论(0)
提交回复
热议问题