0

I have a set of events, each one runs on its own timer. I have multiple use cases but for simplicity let's say they are for individual animation events. Some events run for a specific amount of time, and some for a certain number of iterations.

I want to call events in sequence using callbacks, so that I can be sure the previous task has finished before it kicks off the next. Add animations I also want to be able to pass parameters to the tasks so that I can control speed for example. I would end up with something like:

runSequence( task1(10, 3,"test"), task5(3,7), task3())

Note: each task() function has it's own setInterval() timer that performs an action.

So I can run group of tasks in sequence in an order of my choosing, each task waiting for the previous one to complete before starting. I could also initiate a different sequence of tasks like 1 second later that would be running in parallel with the first sequence.

runSequence( task1(10, 3,"test"), task5(3,7), task3())
wait(1000) // the previous sequence is still running even after this wait period.
runSequence (task2(), task4(5,7)). //these tasks happen in order

I am unsure how to achieve this. I may be able to come up with something that works but may not be elegant or the best practice way to do it.

Thanks in advance for any advice!

TKoL
  • 13,158
  • 3
  • 39
  • 73
Andy
  • 1

1 Answers1

0

What you want is to make functions that return functions that return promises. Async promises return functions, so this might be the answer you're looking for:

Let's start with task1(10, 3,"test"):

function task1(duration, distance, elementId) {
    return async () => {
        // do some logic here with your arguments, setting animations going
        // if you want to do it dirty, just await the duration argument
        await new Promise(resolve => setTimeout(resolve, duration));
    }
}

Now if you have many such functions structured similarly to above - functions that return functions that return promises - then you're ready to start defining your runSequence function

Something like so:

async function runSequence(sequence) {
    const results = [];
    for (let func of sequence) {
        const result = await func();
        results.push(result);
    }
    return results;
}

Which will then allow you to do something like

runSequence([task1(10, 3,"test"), task1(50, 2,"test2"), task1(15, 15,"test3")])

Each task passed to runSequence will happen in order, but two separate runSequence calls can be made to make two separate sequences happen simultaneously.

TKoL
  • 13,158
  • 3
  • 39
  • 73