I have some code in jQuery that iterate through children in div using each(). Every text inside is splitted into words. Each word is processed with 'for' loop. This function can take a long time and can freeze the browser so...
Is there a way to create asynchronous loop inside another asynchronous loop but one is waiting for other to finish?
Could anyone tell me the right direction?
I came up with something like this:
var queue = [];
var nlevel = 0;
function work() {
nlevel = queue.length-1;
var arr = queue[nlevel][0];
var process = queue[nlevel][1];
var cnt = queue[nlevel][2];
var item = arr[cnt];
process.apply(item);
cnt++;
queue[nlevel][2] = cnt;
if (cnt < arr.length) {
setTimeout(work, 1);
} else {
if (queue.length>1) {
queue.pop();
setTimeout(work, 1);
}
}
}
function each(arr, process) {
queue.push([arr, process, 0]);
setTimeout(work, 1);
}
each(['one', 'two', 'three'], function() {
alert(this);
each([1, 2, 3, 4], function() {
alert(this);
});
});
but It has some major bug and I couldn't fix it.