Last active
August 29, 2015 14:02
-
-
Save shimondoodkin/004afd112dcee960c717 to your computer and use it in GitHub Desktop.
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
//suppose you want to insert 15000000 rows to database | |
// i can tell you the future your program will crush | |
// because of background processes will be full to to the limits of the buffers for I/O | |
// so to not crush the system you have to let go everynow and then | |
// | |
//for(var i=0;i<a.length;i++) | |
//{ | |
//} | |
function forloop(from_i,to_i,fn,done,max_continious_loops_i) | |
{ | |
var i=from_i; | |
if(!max_continious_loops_i)max_continious_loops_i=3000; | |
function loop() | |
{ | |
for(;i<to_i&&max_continious_loops_i>=0;i++,max_continious_loops_i--) | |
fn(i); | |
if(i<to_i) setTimeout(loop,150)// let rest every loop for 100ms to do other events processing | |
else if(done)done(); | |
} | |
setTimeout(loop,50)// let return immediately | |
} | |
//example1: | |
//forloop(0,30,function(i){console.log(new Date().getTime(),i)},function(){console.log('done')},10) | |
//example2: | |
// var arr=[1,2,3] | |
// forloop(0,arr.length,function(i) | |
// { | |
// console.log(new Date().getTime(),arr[i]) | |
// },function() | |
// { | |
// console.log('done') | |
// }) | |
//for(var i=0;i<a.length;i++) | |
//{ | |
//} | |
function asyncforloop(from_i,to_i,fn,done,max_continious_loops) | |
{ | |
var i=from_i; | |
if(!max_continious_loops)max_continious_loops=max_continious_loops; | |
var max_continious_loops_i=max_continious_loops | |
function loop() | |
{ | |
function next_end() | |
{ | |
max_continious_loops_i=max_continious_loops; | |
if(i<to_i) setTimeout(loop,150)// let rest every loop for 100ms to do other events processing | |
else if(done)done(); | |
} | |
var maxdeepi=0; | |
function next() | |
{ | |
i++;max_continious_loops_i--; | |
if(maxdeepi++>2000){maxdeepi=0;setTimeout(run,0);} | |
else run(); | |
} | |
function run() | |
{ | |
if(i<to_i&&max_continious_loops_i>0) | |
fn(i,next); | |
else | |
next_end() | |
} | |
run() | |
} | |
setTimeout(loop,50)// let return immediately | |
} | |
//example1: | |
//forloop(0,30,function(i,cb){console.log(new Date().getTime(),i);cb();},function(){console.log('done')},10) | |
//example2: | |
// var arr=[1,2,3] | |
// forloop(0,arr.length,function(i,cb) | |
// { | |
// console.log(new Date().getTime(),arr[i]) | |
// cb(); | |
// },function() | |
// { | |
// console.log('done') | |
// }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment