Want to deal with heavy-load processing of displayed data in the browser? If your major concern is not to freeze UI during lengthy javascript processing you developed, you can refactor loop bodies into sequential steps, such that each step call its next by using window.setTimeout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | var pr = function(x) {console.log(x)}; var COUNT=3; // original regular javascript loop for(var i=0; i<COUNT; i++) { var msg = "current index is (" + i + ")"; pr(msg); } // step-by-step sequential calls var body = function(i) { var msg = "non-blocking for: index is (" + i + ")"; pr(msg); } nonBlockingFor(body, 4); |
The function nonBlockingFor calls the first argument (as a function) the number of times passed as second argument. It’s definition follows:
1 2 3 4 5 6 7 8 9 10 11 | // function constructor var nonBlockingFor = (function() { function _run(context) { if(context.idx > context.max) return; context.fnc(context.idx++); window.setTimeout((function(){ _run(context)}), 1); } return (function _start(ufn, uqt, runId) { _run({idx: 0, max: uqt -1, fnc: ufn || (function(){}), runId: runId}); }); })(); |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.