JavaScript, Node.js: is Array.forEach asynchronous?

The Solution to JavaScript, Node.js: is Array.forEach asynchronous? is

No, it is blocking. Have a look at the specification of the algorithm.

However a maybe easier to understand implementation is given on MDN:

if (!Array.prototype.forEach)
  Array.prototype.forEach = function(fun /*, thisp */)
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
      if (i in t), t[i], i, t);

If you have to execute a lot of code for each element, you should consider to use a different approach:

function processArray(items, process) {
    var todo = items.concat();

    setTimeout(function() {
        if(todo.length > 0) {
            setTimeout(arguments.callee, 25);
    }, 25);

and then call it with:

processArray([many many elements], function () {lots of work to do});

This would be non-blocking then. The example is taken from High Performance JavaScript.

Another option might be web workers.

~ Answered on 2011-02-19 10:47:45

Most Viewed Questions: