實(shí)現(xiàn)一個簡單的js隊列
class Queue {
constructor() {
this.isPadding = false;
this.queueList = [];
}
push(fn) {
this.queueList.push(fn);
this.run()
}
size() {
return this.queueList.length;
}
run() {
const vm = this;
if (!this.size() || this.isPadding) { // 當(dāng)前隊列為空,或者當(dāng)前有異步還未執(zhí)行完成
return
}
this.isPadding = true;
const item = this.queueList.shift();
item(function done() {
vm.isPadding = false;
vm.run()
})
}
}
const request = new Queue();
request.push(function (done) {
setTimeout(() => {
console.log('異步1')
done()
}, 2000)
})
request.push(function (done) {
setTimeout(() => {
console.log('異步2')
done()
}, 2000)
})
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者