const queue = []let queueRunning = falselet loopTimer = nullconst loop = task => { // do something... console.log(task) if (isQueueHasTask()) { // you can add new tasks in the middle of the queue. loopTimer = setTimeout(() => {loop(getNextTask())}) } else { queueRunning = false }}const startLoop = () => { if (queueRunning) return if (isQueueHasTask()) { queueRunning = true loop(getNextTask()) }}const stopLoop = () => { if (!queueRunning) return if (loopTimer) { clearTimeout(loopTimer) queueRunning = false }}const getNextTask = () => queue.shift()const isQueueHasTask = () => !!queue.lengthconst addTask = task => { if (!Array.isArray(task)) task = [task] queue.push(...task) startLoop()}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)