Created
May 18, 2016 09:07
-
-
Save Ginhing/1d3a8f10fba472db1eca268c3faa1125 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
/** | |
* @typedef {{delay: number, concurrent: number, holdOn: boolean, onHoldMax: (number|boolean)}} Option | |
*/ | |
/** | |
* 用于应对大量的输入,有如下方式: | |
* - 对所有入队的数据按一定的时间间隔,逐个处理 | |
* - 当固定的时间间隔内没有新输入,或到达一定时间,对当前整个队列处理 | |
* @param handler | |
* @param {Option} options | |
* @returns {Object} | |
*/ | |
handleInQueue: function (handler, options) { | |
options = options || {} | |
var queue = [], | |
i = 0, // number of tasks have been handled | |
waiting = false, | |
timer | |
var delay = options.delay || 100 | |
var concurrent = options.concurrent || 1 | |
var holdOn = !!options.holdOn | |
var onHoldMax = options.onHoldMax || false | |
function run(func, queue) { | |
i += queue.length | |
queue.forEach(function (args) { | |
func.apply(null, args) | |
}) | |
timer = setTimeout(next, delay) | |
} | |
function next() { | |
if (queue.length - i > 0) { | |
if (i > 100) { | |
queue = queue.slice(i) | |
i = 0 | |
} | |
run(handler, queue.slice(i, i + concurrent)) | |
} else { | |
clean() | |
} | |
} | |
function clean() { | |
window.clearTimeout(timer) | |
queue = [] | |
i = 0 | |
waiting = false | |
} | |
function runAll() { | |
queue.length && handler(queue) | |
clean() | |
} | |
return { | |
add: function () { | |
var args = [].slice.call(arguments, 0) | |
if(holdOn){ | |
window.clearTimeout(timer) | |
timer = setTimeout(runAll, delay) | |
if (onHoldMax && !waiting) { | |
waiting = true | |
setTimeout(runAll, onHoldMax) | |
} | |
} else { | |
if (queue.length === 0) { | |
setTimeout(run, 0, handler, [args]) | |
} | |
} | |
queue.push(args) | |
}, | |
rightNow: handler, | |
reset: clean | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment