问题
I'm currently running 2 for-loops, going through 2 arrays of objects and creating a new array with the objects which occur in both lists. When the lists become to large, I get a "Stop running script" prompt.
MineGlobals.receivedData = jQuery.parseJSON(MineGlobals.receivedDataRaw);
MineGlobals.nettStasjonsListe = new Array();
var len1 = MineGlobals.nsData.length;
var len2 = MineGlobals.receivedData.Nettstasjoner.length
for (var i = 0; i < len2; i++) {
for (var j = 0; j < len1; j++) {
if (MineGlobals.receivedData.Nettstasjoner[i].Id == MineGlobals.nsData[j].Id) {
var obj = new nsObject();
obj = MineGlobals.nsData[j];
if (MineGlobals.nsData[j].Lg != 0 && MineGlobals.nsData[j].La != 0) {
MineGlobals.nettStasjonsListe.push(obj);
}
break;
}
}
}
I tried with setTimeout(), but can't get it to work... So any ideas?
EDIT
So since I am a new user I can't answer my own question but I managed to find the solution. I used a associativeArray(). Placing the largest array in it, with the ID as key, and then iterating over it to find the identical IDs.
var associativeArray = {};
for (var i = 0; i < len1; i++) {
associativeArray[MineGlobals.nsData[i].Id] = MineGlobals.nsData[i];
}
for (var j = 0; j < len2; j++) {
var obj = new nsObject();
obj = associativeArray[MineGlobals.receivedData.Nettstasjoner[j].Id];
if (obj != undefined) {
if (obj.Lg != 0 && obj.La != 0) {
if (obj == null || obj == "") {
obj.Nvn = "Ikke definert";
}
if (obj.NisAdresse == null || obj.NisAdresse == "") {
obj.NisAdresse = "Ikke definert";
}
MineGlobals.nettStasjonsListe.push(obj);
}
}
}
回答1:
You can chunk
the array processing, see the following link:
I wrote a prototype class around it and it solved my problem regarding this:
/**
* provides UI update while using large arrays without blocking
* found core idea on http://www.mattsnider.com/javascript/handle-slow-processes-without-blocking-the-ui/
*/
var ChunkedArray = Class.create(Enumerable, {
initialize: function(options) {
this.array = new Array();
this.options = Object.extend({
chunkSize: 20,
interval: 10
}, options || {})
},
push: function(obj) {
this.array.push(obj)
},
chunk: function(array, index, length, iterator, context) {
var j, l = array.length;
for (j = (index + length); (index < j && index < l); index += 1) {
iterator.call(context, array[index], index);
}
if (l > index) {
setTimeout(function() {
this.chunk(array, index, length, iterator, context);
}.bind(this), this.options.interval);
}
},
_each: function(iterator, context) {
this.chunk(this.array, 0,
this.options.chunkSize, iterator, context);
},
toString: function() {
return this.array.toString();
}
});
来源:https://stackoverflow.com/questions/11155244/prevent-stop-running-script-when-loading-large-amounts-of-data