The situation is that I am dynamically loading a set of scripts from an API that I then call via eval()
. I don't care which order the scripts are called, but I don't want any of them to be called at the same time. That is, scripts A, B, and C can be returned in order C, B, A, and I want to begin eval(C)
immediately when C is returned, but I want eval(B)
to wait until eval(C)
is completed.
Without getting into the fully hairy code, here is the heart of it where "instances" is a string array.
$.each(instances, function( index, instance ) {
var apiUrl = "http://the-api-url.com/" + instance;
$.getJSON(apiUrl, function(data) {
// except I don't want to eval here as evaluations may overlap
eval(data.script);
});
});
From what I understand, I could use .when()
to wait until all were complete, but that would waste time as I don't need to wait until all are downloaded in order to begin their execution.
It's a bit unclear from your question, but assuming that the scripts can be executed in any order (A, B, C
, A, C, B
, B, A, C
, etc.) then you don't have to change anything.
Javascript (in the browser) is single threaded, so the callbacks you are passing to $.getJSON
will be scheduled serially.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With