G
G
greenredero2018-12-08 01:10:53
JavaScript
greenredero, 2018-12-08 01:10:53

How effective is this code?

I'm new to programming, so I apologize in advance if this is a noob question.
The bottom line is that you need to process an array of arrays with some delays (I'm doing css manipulations). After some googling, I came up with this code:

let arr = ["abc", "defg", "hijkl", "mnopqr"];

const asyncForEach = async (array, callback) => {
  for (let index = array.length - 1; index >= 0; --index) {
    await callback(array[index], index, array)
  }
}

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))

let doWork = (obj, innerMs, ms) => new Promise(r => setTimeout(async function () {
    for (let i = 0; i < obj.length; ++i) {
        console.log(obj[i]);
        await waitFor(innerMs);
    }
    console.log("=================");
    r();
}, ms))

const start = async () => {
    await asyncForEach(arr, async (string, index, array) => {
      await doWork(string, 250, 1000)
    })
    console.log('Done')
  }
  
start()

On each iteration of the main array, Promise objects are created. But also for the smoothness of the animation, I will need delays for each internal array (in the example these are just strings, in fact - a change in the element styles cycle), and here I had doubts. There can be quite a lot of objects depending on the complexity of the animation (well, or the size of the lines, as in the example), is it possible to somehow optimize this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-12-08
@greenredero

requestAnimationFrame()

window.requestAnimationFrame tells the browser that you want to animate and asks it to schedule a redraw on the next animation frame. As a parameter, the method receives a function that will be called before redrawing.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question