Does javascript execution stop when an invalid line is encountered?

后端 未结 4 2227
孤独总比滥情好
孤独总比滥情好 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: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.

提交回复
热议问题