Last active
November 1, 2016 12:43
-
-
Save m99coder/b34c0289d8741c46374619d7579707a1 to your computer and use it in GitHub Desktop.
Non-blocking execution of expensive function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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