Last active
March 13, 2017 12:31
-
-
Save hereisfun/2c52cddebca5db78d531b6c955e3ba55 to your computer and use it in GitHub Desktop.
分时函数,将一次性大批量的操作分割成多次小批量
This file contains 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
//ary为要批量处理的数据,fn为对每个数据的操作方式,count为每次处理的量 | |
var timechunk = function(ary, fn, count){ | |
var obj, | |
timer; | |
var start = function(){ | |
for(var i = 0; i < count; i++){ | |
if(ary.length === 0){ | |
return; | |
} | |
obj = ary.shift(); | |
fn(obj); | |
} | |
} | |
return function(){ | |
start();//首次执行不用延后 | |
timer = setInterval(function(){ | |
if(ary.length === 0){ | |
clearInterval(timer); | |
timer = null; | |
return; | |
}else{ | |
start(); | |
} | |
}, 1000); | |
//时间间隔也可以通过参数指定 | |
} | |
} | |
var data = [1,2,3,4,5,6,7,8,9,10]; | |
function print(i){ | |
console.log(i); | |
} | |
var printPer3 = timechunk(data, print, 3); | |
printPer3(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment