Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const QUEUE = [];
- let running = false;
- function next() {
- console.log('nexting')
- if(QUEUE[0]) {
- running = true;
- const promise = QUEUE.shift();
- promise().then(function(){
- console.log('2000 buffer')
- setTimeout(next, 2000);
- });
- } else {
- running = false;
- }
- }
- function addToQueue(promise) {
- QUEUE.push(promise);
- if (!running) {
- next();
- }
- }
- const PromiseOne = () => new Promise(function(resolve, reject) {
- console.log('starting promise one, timeout 5000');
- setTimeout(function() {
- console.log('resolving promise one');
- resolve();
- }, 5000);
- });
- const PromiseTwo = () => new Promise(function(resolve, reject) {
- console.log('starting promise two, timeout 3000');
- setTimeout(function() {
- console.log('resolving promise two');
- resolve();
- }, 3000);
- });
- const PromiseThree = () => new Promise(function(resolve, reject) {
- console.log('starting promise three, timeout 6000');
- setTimeout(function() {
- console.log('resolving promise three');
- resolve();
- }, 6000);
- });
- const PromiseFour = () => new Promise(function(resolve, reject) {
- console.log('starting promise four, timeout 1000');
- setTimeout(function() {
- console.log('resolving promise four');
- resolve();
- }, 1000);
- });
- addToQueue(PromiseOne);
- addToQueue(PromiseTwo);
- setTimeout(function() {
- addToQueue(PromiseThree);
- }, 1000);
- setTimeout(function() {
- addToQueue(PromiseFour);
- }, 7000);
- setTimeout(function() {
- addToQueue(PromiseFour);
- }, 30000);
Add Comment
Please, Sign In to add comment