What is the most efficient way to iterate through large object elements without freezing the browser?
I have successfully looped through arrays using setTimeout
/setInterval
in this manner:
var i = 0;
var l = arr.length;
var interval = window.setInterval(function(){
var k = 100; // process 100 items on each Timeout
var element;
while(k--) {
if (i == l) {
return clearInterval(interval);
}
element = arr[i++];
// ... work here ...
}
}, 100);
But when dealing with very large objects, what other methods can I use?
- Iterating through keys using
for(k in arr)
will create one large loop that should be avoided. - It's not possible to use
.splice()
on objects since they are not arrays.
Currently, I resort to creating an array like this
[{k: .., v:...},{k: .., v:...},{k: .., v:...},{k: .., v:...},{k: .., v:...},{k: .., v:...},{k: .., v:...},...]
, but it feels like a wasteful use of space.