Skip to content

Instantly share code, notes, and snippets.

@kjaquier
Last active August 29, 2015 14:10
Show Gist options
  • Save kjaquier/3cbd7dbf4eef1aca267e to your computer and use it in GitHub Desktop.
Save kjaquier/3cbd7dbf4eef1aca267e to your computer and use it in GitHub Desktop.
Perform a long computation with pauses between steps, for the UI to be able to render and not freeze.
// Inspired from : http://www.sitepoint.com/multi-threading-javascript/
longOperation: function (fn, initData, interval) {
var data = initData, busy = false;
var result = $q.defer();
var taskId;
var task = function() {
if(!busy) {
busy = true;
var res = fn(data);
data = res.data;
if (res.continueWhile === undefined) {
throw new Error("Result doesn't define 'continueWhile' !");
}
if(!res.continueWhile) {
clearInterval(taskId);
result.resolve(data);
}
busy = false;
}
};
return {
run: function() {
taskId = setInterval(task, interval);
return result.promise;
}
};
}
// Example using Angular's $q for promises
var op = AsyncHelper.longOperation(function(data) {
var a = data.array;
var n = data.array.length;
var i = data.i;
var upBound = Math.min(i + data.step - 1, n);
$log.info("from " + i + " to " + upBound);
while (i < upBound) {
for (var j = 0; j < 100; j++) {
a[i++] += Math.floor(Math.random() * 10);
}
}
return {
data: {
array: a,
i: i+1,
step: data.step
},
continueWhile: data.i < n
};
}, {
array: new Uint32Array(N),
i: 0,
step: Math.floor(N / 10)
}, 20);
op.run().then(function(data) {
$log.info("final value : array[42] = " + data.array[42]);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment