Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forEach parallel in Javascript?

I want to apply a function to all elements in an array at the same time, I dont want to apply it one by one, I mean, sequentially. Its because I have a big array of elements and I want to draw them in a Canvas at the same time. Im working with Angular 6.

I have this:

 drawRow(row: Node[]) {
    row.forEach((item) => {
      this.addToCanvas(item);
    });
 }

I want to add to the canvas all the elements of the row in parallel. Is necessary to install some library to do this or can I do this just with pure javascript...? What would be the correct approach to this ?

Thank you in advance =)

like image 939
Kimy BF Avatar asked Apr 30 '26 12:04

Kimy BF


1 Answers

Like Pointy mentioned in comment, javascript is mostly single threaded.

If you find lag because the canvas is large, you can promisify addToCanvas. what it will do is defer the invocation of these function in the future, permitting the page to be interacted between each invocation.

If you have to do something after all "addToCanvas" have been called, you can use Promise.all()

To do truly parallel work, you would need to work with WebWorker, but these have limitation. They don't have access to the DOM, and can only be interacted with a asynchronous message API. Depending of your need, it could be a solution. It is useful if you have long calculation you want to do in the background.

like image 92
Félix Brunet Avatar answered May 03 '26 02:05

Félix Brunet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!