Set UP:
Hi. I am trying to learn about creating/instantiating objects. I was thinking I should be able to create multiple objects that may have different amounts of similar works (like gather news articles) and would “report completion” regardless of the order created. So far I am not clear on this, so here is a basic example followed by the stated question:
function test(count){
this.count = count;
for(var i = 0; i< count; i++){}
console.log(i);
}
new test(1000);
new test(10);
Actual Question:
Based on the code above, I would expect the second instance to print first, but it does not. What would be the correct way to set this up so that which ever object finishes its work would print first?
* Modify my question *
Sorry…what I am really intending to ask is how to set objects to have more of an asynchronous behavior. I am new to Stack, so please let me know if I should close/move this question.
In general JavaScript is uses a synchronous execution model, the event queue. All calls are placed here, basically in the order they appear in your source code (respecting the scope they are in).
So if you start some function, nothing else is executed until that very function is finished. In your case you place both calls on the event queue, but the second call will only be executed, when the first one has finished.
There, however, exceptions: Worker or AJAX requests.
Here the execution is outside the usual event queue and you use message handlers or callbacks to use the results, after the execution is finished. In most cases, however, you can’t be sure in which order the calls are finished as there are many circumstances affecting the ordering of execution (network delay, cpu usage, etc.)
In your case, it seems, you want to load external resources, anyway. So have a look at how AJAX works.