Skip to content

Instantly share code, notes, and snippets.

@m99coder
Last active November 1, 2016 12:43
Show Gist options
  • Select an option

  • Save m99coder/b34c0289d8741c46374619d7579707a1 to your computer and use it in GitHub Desktop.

Select an option

Save m99coder/b34c0289d8741c46374619d7579707a1 to your computer and use it in GitHub Desktop.
Non-blocking execution of expensive function
var data = [1, 2, 3];
var REFRESH_RATE = 16.67;
function veryExpensive(item) {
// ...
}
function forEachExpensive(data, callback) {
var index = 0;
var dataLength = data.length;
return new Promise(function(success) {
var callRecursively = function() {
callback(data[index]);
index++;
window.setTimeout(function() {
if (index < dataLength) {
callRecursively();
} else {
success();
}
}, REFRESH_RATE);
};
callRecursively();
});
}
forEachExpensive(data, veryExpensive).then(() => console.log('done'));
forEachExpensive(data, veryExpensive).then(() => console.log('done'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment