Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let actionsQueue = {};
- let defaultMaxActionsProgressing = 50;
- let lastActionId = 0;
- export const getQueue = (key) => {
- if (!actionsQueue[key]) {
- actionsQueue[key] = {
- max: defaultMaxActionsProgressing,
- actions: []
- };
- }
- return actionsQueue[key];
- };
- export const setMax = (key, max) => {
- getQueue(key).max = max;
- };
- const removeFromQueue = (key, id) => {
- let q = getQueue(key);
- q.actions = q.actions.filter(a => a.id !== id);
- };
- const execute = (key, action) => {
- // setting action to progressing
- action.progressing = true;
- action.fn(() => {
- removeFromQueue(key, action.id);
- executeQueue(key);
- });
- };
- const executeQueue = (key) => {
- let q = getQueue(key);
- const actualProgressing = q.actions.filter(a => a.progressing).length;
- if (q.actions.length === 0 || actualProgressing >= q.max) {
- return;
- }
- q.actions
- .filter(a => !a.progressing)
- .slice(0, q.max - actualProgressing)
- .map(action => execute(key, action));
- };
- export const addToExecute = (key, fn) => {
- let q = getQueue(key);
- q.actions.push({
- id: lastActionId,
- key,
- fn,
- progressing: false
- });
- lastActionId++;
- executeQueue(key);
- };
- // WYWOŁANIE
- setMax('test-key', 4);
- console.time('1')
- console.time('2')
- console.time('3')
- console.time('4')
- console.time('5')
- // PIERWSZE WYWOŁANIE
- addToExecute('test-key', (end) => {
- setTimeout(() => {
- console.timeEnd('1');
- end()
- }, 200);
- })
- // DRUGIE WYWOŁANIE
- addToExecute('test-key', (end) => {
- setTimeout(() => {
- console.timeEnd('2');
- end()
- }, 200);
- })
- // TRZECIE WYWOŁANIE
- addToExecute('test-key', (end) => {
- setTimeout(() => {
- console.timeEnd('3');
- end()
- }, 200);
- })
- addToExecute('test-key', (end) => {
- setTimeout(() => {
- console.timeEnd('4');
- end()
- }, 200);
- })
- addToExecute('test-key', (end) => {
- setTimeout(() => {
- console.timeEnd('5');
- end()
- }, 200);
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement