开发者

Does JavaScript execute top to bottom?

开发者 https://www.devze.com 2022-12-14 22:59 出处:网络
Does the code (e.g. functions) execute 开发者_如何学Goat the same time or does it follows the order in which it was written (top to bottom)? I know that order matters in HTML, what about JavaScript?

Does the code (e.g. functions) execute 开发者_如何学Goat the same time or does it follows the order in which it was written (top to bottom)? I know that order matters in HTML, what about JavaScript?

For instance, if there are two function calls one after the other, will they get executed simultaneously or one after the other even if they have nothing to do with each other?


It may seem as if Javascript functions are executing in an unpredictable order because the model for Javascript in a browser is event-driven. This means that a Javascript program typically attaches event handlers to DOM elements and these are triggered by user actions such as clicking or moving the pointer over an element. However, the script that sets up the event handlers runs as a traditional structured imperative program.

A further complication is that modern Javascript applications make extensive use of asynchronous functions. This means that a function call might return quickly but will have set in motion an action which completes at a later time. An obvious example is the sending of requests to a server in so-called AJAX applications. Typically the request function is passed a callback function which is called when the request completes. However the Javascript program will go on to the next statement without waiting for the completion of the request. This can be somewhat confusing if you aren't thinking clearly enough about what your program is actually doing.

Another example that you might sometimes encounter is the launching of animations in jQuery. These too work asynchronously and you can pass a callback function that runs after the animation completes. Once again this can be surprising sometimes if you expect the next statement to be executed after the animation completes rather than after it starts.


It occurs in the order it was written (with various exceptions). More specifically it's an imperative structured object-oriented prototype based scripting language :)

See Imperative Programming

0

精彩评论

暂无评论...
验证码 换一张
取 消