Re0:从零开始的JavaScript - 可暂停异步任务队列的3种方式 发表于 2018-06-24 | 分类于 前端 | 字数统计 282 | 阅读时长 2 实现可暂停异步任务队列的3种方式需求:在爬取网页的时候需要同时向多个分页进行爬取,并能够进行爬取中间暂停。12345678910111213141516171819202122232425262728let builder = x => async () => Promise.resolve(x);let tasks = Array.from({ length:1120 }).map((_, k) => builder(`console.log(${k})`))let index = 0;let timer;let canRun = true;function run(){ index++; timer = setTimeout(async () => { let funcSource = await tasks[index](index); let func = new Function(funcSource); func() if (canRun) { run() }else{ clearTimeout(timer) } })}run()setTimeout(function () { console.log("change canRun") canRun = false;}, 10) 1234567891011121314151617181920212223242526272829function sleep(milliSeconds) { var startTime = new Date().getTime(); while (new Date().getTime() < startTime + milliSeconds);};const getRandom = async () => { sleep(300) return Math.random() > 0.1;}let builder = x => async () => Promise.resolve(x);let tasks = Array.from({ length: 1120}).map((_, k) => builder(`console.log(${k})`))async function run() { for (let task of tasks) { let random = await getRandom() if (random) { let source = await task(); (new Function(source))() }else{ break; } }}run() 12345678910111213141516171819202122232425262728293031323334353637383940414243444546const EventEmitter = require('events');let builder = x => async () => Promise.resolve(x);let tasks = Array.from({ length:1120 }).map((_, k) => builder(`console.log(${k})`))function sleep(milliSeconds) { var startTime = new Date().getTime(); while (new Date().getTime() < startTime + milliSeconds); };const getRandom = async () => { sleep(300) return Math.random() > 0.1;}class Queue extends EventEmitter { constructor() { super(); this._index = 0; this._start(); } _start() { this._timer = setTimeout(async () => { const source = await tasks[this._index]() this.emit('next', source); this._index++; this._start(); }, 0); } _stop(){ clearTimeout(this._timer) }};let q = new Queue();q.on('next', async (source) => { (new Function(source))()});setTimeout(()=>{ q._stop()}, 100) -------------本文结束感谢您的阅读-------------