I would recommend breaking it up and iterating using setTimeout.
For example, instead of:
function example1() { for (var i = 0; i < 1000; i++) {
You can write:
function example2() { var i = 0; helper(); function helper() {
You do not need to have every iteration in another callback. You can convert 1000 iterations to 1 function call for 10 iterations per function call in 100 function calls or something that would be most appropriate in your case. The idea is to not block the user interface for so long that the user will notice.
Another idea is to use Web Workers if possible, but this will not work in older browsers (which may or may not be a problem for you if you write a browser extension or know what your users will use, etc.) .
If you do this as you explained in your question, then you will make the browser completely irresponsible during your calculations, and you will most likely run a "slow script - do you want to kill it?" kind of warning.
source share