开发者

how to make sure some piece of code is executed before all other codes in java script?

开发者 https://www.devze.com 2023-03-11 19:34 出处:网络
I am a newbie in javascript and what makes me so confused in the order of operations in Javascript. le开发者_StackOverflow中文版ts suppose I have a following code:

I am a newbie in javascript and what makes me so confused in the order of operations in Javascript.

le开发者_StackOverflow中文版ts suppose I have a following code:

var myArray = [];
function getArray(x){
var _array = [];
.... {the code here is pretty big}
return _array;
}
myArray = getArray(1);

and rest of the code are all based on myArray. Unfortunately, using this code sometimes myArray is not set in time so the rest of code doesn't work properly. Is there anyway that I can make sure the rest of the code is executed when myArray is set properly?

Thanks,

Amir.


Place it at the top of the js file or html before any other javascript and it will execute first. This assumes you don't have it wrapped in some sort of delay like setTimeout or jQuery's document ready function.

JS executes as it is loaded by the web browser, so the order it appears in determines the order it executes in relative to other JS.


> var myArray = [];

There are two phases to javascript processing: the first processes all declarations, the second executes the code. So regardless of where myArray is declared, it will be declared before any code is executed.

When code execution begins, statements are executed in sequence so myArray is assigned an empty array before the following code is executed.

>  function getArray(x) { 
>    var _array = []; ....
>    // the code here is pretty big
>     return _array;
>  } 

Similarly, getArray will also be defined before any code is run.

>  myArray = getArray(1);

This replaces the array assigned to myArray above with whatever is returned by getArray.

If, from time to time, the value of myArray is not what you expect, then it is a consequence of whatever is being returned by getArray, so I would concentrate on that.

0

精彩评论

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