How to make non-blocking javascript code?

46,599

Solution 1

SetTimeout with callbacks is the way to go. Though, understand your function scopes are not the same as in C# or another multi-threaded environment.

Javascript does not wait for your function's callback to finish.

If you say:

function doThisThing(theseArgs) {
    setTimeout(function (theseArgs) { doThatOtherThing(theseArgs); }, 1000);
    alert('hello world');
}

Your alert will fire before the function you passed will.

The difference being that alert blocked the thread, but your callback did not.

Solution 2

To make your loop non-blocking, you must break it into sections and allow the JS event processing loop to consume user events before carrying on to the next section.

The easiest way to achieve this is to do a certain amount of work, and then use setTimeout(..., 0) to queue the next chunk of work. Crucially, that queueing allows the JS event loop to process any events that have been queued in the meantime before going on to the next piece of work:

function yieldingLoop(count, chunksize, callback, finished) {
    var i = 0;
    (function chunk() {
        var end = Math.min(i + chunksize, count);
        for ( ; i < end; ++i) {
            callback.call(null, i);
        }
        if (i < count) {
            setTimeout(chunk, 0);
        } else {
            finished.call(null);
        }
    })();
}

with usage:

yieldingLoop(1000000, 1000, function(i) {
    // use i here
}, function() {
    // loop done here
});

See http://jsfiddle.net/alnitak/x3bwjjo6/ for a demo where the callback function just sets a variable to the current iteration count, and a separate setTimeout based loop polls the current value of that variable and updates the page with its value.

Solution 3

There are in general two ways to do this as far as I know. One is to use setTimeout (or requestAnimationFrame if you are doing this in a supporting environment). @Alnitak shown how to do this in another answer. Another way is to use a web worker to finish your blocking logic in a separate thread, so that the main UI thread is not blocked.

Using requestAnimationFrame or setTimeout:

//begin the program
console.log('begin');
nonBlockingIncrement(100, function (currentI, done) {
  if (done) {
    console.log('0 incremented to ' + currentI);
  }
});
console.log('do more stuff'); 

//define the slow function; this would normally be a server call
function nonBlockingIncrement(n, callback){
  var i = 0;
  
  function loop () {
    if (i < n) {
      i++;
      callback(i, false);
      (window.requestAnimationFrame || window.setTimeout)(loop);
    }
    else {
      callback(i, true);
    }
  }
  
  loop();
}

Using web worker:

/***** Your worker.js *****/
this.addEventListener('message', function (e) {
  var i = 0;

  while (i < e.data.target) {
    i++;
  }

  this.postMessage({
    done: true,
    currentI: i,
    caller: e.data.caller
  });
});



/***** Your main program *****/
//begin the program
console.log('begin');
nonBlockingIncrement(100, function (currentI, done) {
  if (done) {
    console.log('0 incremented to ' + currentI);
  }
});
console.log('do more stuff'); 

// Create web worker and callback register
var worker = new Worker('./worker.js'),
    callbacks = {};

worker.addEventListener('message', function (e) {
  callbacks[e.data.caller](e.data.currentI, e.data.done);
});

//define the slow function; this would normally be a server call
function nonBlockingIncrement(n, callback){
  const caller = 'nonBlockingIncrement';
  
  callbacks[caller] = callback;
  
  worker.postMessage({
    target: n,
    caller: caller
  });
}

You cannot run the web worker solution as it requires a separate worker.js file to host worker logic.

Solution 4

Using ECMA async function it's very easy to write non-blocking async code, even if it performs CPU-bound operations. Let's do this on a typical academic task - Fibonacci calculation for the incredible huge value. All you need is to insert an operation that allows the event loop to be reached from time to time. Using this approach, you will never freeze the user interface or I/O.

Basic implementation:

const fibAsync = async (n) => {
  let lastTimeCalled = Date.now();

  let a = 1n,
    b = 1n,
    sum,
    i = n - 2;
  while (i-- > 0) {
    sum = a + b;
    a = b;
    b = sum;
    if (Date.now() - lastTimeCalled > 15) { // Do we need to poll the eventloop?
      lastTimeCalled = Date.now();
      await new Promise((resolve) => setTimeout(resolve, 0)); // do that
    }
  }
  return b;
};

And now we can use it (Live Demo):

let ticks = 0;

console.warn("Calulation started");

fibAsync(100000)
  .then((v) => console.log(`Ticks: ${ticks}\nResult: ${v}`), console.warn)
  .finally(() => {
    clearTimeout(timer);
  });

const timer = setInterval(
  () => console.log("timer tick - eventloop is not freezed", ticks++),
  0
);

As we can see, the timer is running normally, which indicates the event loop is not blocking.

I published an improved implementation of these helpers as antifreeze2 npm package. It uses setImmediate internally, so to get the maximum performance you need to import setImmediate polyfill for environments without native support.

Live Demo

import { antifreeze, isNeeded } from "antifreeze2";

const fibAsync = async (n) => {
  let a = 1n,
    b = 1n,
    sum,
    i = n - 2;
  while (i-- > 0) {
    sum = a + b;
    a = b;
    b = sum;
    if (isNeeded()) {
      await antifreeze();
    }
  }
  return b;
};

Solution 5

You cannot execute Two loops at the same time, remember that JS is single thread.

So, doing this will never work

function loopTest() {
    var test = 0
    for (var i; i<=100000000000, i++) {
        test +=1
    }
    return test
}

setTimeout(()=>{
    //This will block everything, so the second won't start until this loop ends
    console.log(loopTest()) 
}, 1)

setTimeout(()=>{
    console.log(loopTest())
}, 1)

If you want to achieve multi thread you have to use Web Workers, but they have to have a separated js file and you only can pass objects to them.

But, I've managed to use Web Workers without separated files by genering Blob files and i can pass them callback functions too.

//A fileless Web Worker
class ChildProcess {
     //@param {any} ags, Any kind of arguments that will be used in the callback, functions too
    constructor(...ags) {
        this.args = ags.map(a => (typeof a == 'function') ? {type:'fn', fn:a.toString()} : a)
    }

    //@param {function} cb, To be executed, the params must be the same number of passed in the constructor 
    async exec(cb) {
        var wk_string = this.worker.toString();
        wk_string = wk_string.substring(wk_string.indexOf('{') + 1, wk_string.lastIndexOf('}'));            
        var wk_link = window.URL.createObjectURL( new Blob([ wk_string ]) );
        var wk = new Worker(wk_link);

        wk.postMessage({ callback: cb.toString(), args: this.args });
 
        var resultado = await new Promise((next, error) => {
            wk.onmessage = e => (e.data && e.data.error) ? error(e.data.error) : next(e.data);
            wk.onerror = e => error(e.message);
        })

        wk.terminate(); window.URL.revokeObjectURL(wk_link);
        return resultado
    }

    worker() {
        onmessage = async function (e) {
            try {                
                var cb = new Function(`return ${e.data.callback}`)();
                var args = e.data.args.map(p => (p.type == 'fn') ? new Function(`return ${p.fn}`)() : p);

                try {
                    var result = await cb.apply(this, args); //If it is a promise or async function
                    return postMessage(result)

                } catch (e) { throw new Error(`CallbackError: ${e}`) }
            } catch (e) { postMessage({error: e.message}) }
        }
    }
}

setInterval(()=>{console.log('Not blocked code ' + Math.random())}, 1000)

console.log("starting blocking synchronous code in Worker")
console.time("\nblocked");

var proc = new ChildProcess(blockCpu, 43434234);

proc.exec(function(block, num) {
    //This will block for 10 sec, but 
    block(10000) //This blockCpu function is defined below
    return `\n\nbla bla ${num}\n` //Captured in the resolved promise
}).then(function (result){
    console.timeEnd("\nblocked")
    console.log("End of blocking code", result)
})
.catch(function(error) { console.log(error) })

//random blocking function
function blockCpu(ms) {
    var now = new Date().getTime();
    var result = 0
    while(true) {
        result += Math.random() * Math.random();
        if (new Date().getTime() > now +ms)
            return;
    }   
}
Share:
46,599

Related videos on Youtube

user1717828
Author by

user1717828

Updated on July 09, 2022

Comments

  • user1717828
    user1717828 almost 2 years

    How can I make a simple, non-block Javascript function call? For example:

      //begin the program
      console.log('begin');
      nonBlockingIncrement(10000000);
      console.log('do more stuff'); 
    
      //define the slow function; this would normally be a server call
      function nonBlockingIncrement(n){
        var i=0;
        while(i<n){
          i++;
        }
        console.log('0 incremented to '+i);
      }
    

    outputs

    "beginPage" 
    "0 incremented to 10000000"
    "do more stuff"
    

    How can I form this simple loop to execute asynchronously and output the results via a callback function? The idea is to not block "do more stuff":

    "beginPage" 
    "do more stuff"
    "0 incremented to 10000000"
    

    I've tried following tutorials on callbacks and continuations, but they all seem to rely on external libraries or functions. None of them answer the question in a vacuum: how does one write Javascript code to be non-blocking!?


    I have searched very hard for this answer before asking; please don't assume I didn't look. Everything I found is Node.js specific ([1], [2], [3], [4], [5]) or otherwise specific to other functions or libraries ([6], [7], [8], [9], [10], [11]), notably JQuery and setTimeout(). Please help me write non-blocking code using Javascript, not Javascript-written tools like JQuery and Node. Kindly reread the question before marking it as duplicate.

    • Andrew Hoffman
      Andrew Hoffman over 9 years
      Effortlessly. You have to actually tell the thread to sleep for a duration in order to block the thread. To avoid sleeping, use timers with callbacks. sitepoint.com/settimeout-example
    • Travis J
      Travis J over 9 years
      There is no way to do this. Javascript is not multi-threaded and can only queue tasks. You can execute long running tasks at a later time, but not at the same time as other tasks.
    • Alnitak
      Alnitak over 9 years
      @AndrewHoffman I'm not sure you understand. You can't tell JS to sleep, but you can keep it so busy that the UI loop can't service any events.
    • Andrew Hoffman
      Andrew Hoffman over 9 years
      You can block the thread with things like alert, which I wish every browser would disable. Bad programmers freezing my browser. -_-'
    • Alnitak
      Alnitak over 9 years
      I believe I may have misunderstood the question having just realised that your "slow loop" was just an example. The answer I've given is the definitive way to break a long running computation into smaller pieces. However in the server call case, Promises are typically the right answer, and are now included in ES6. That said, any long-running async task API should provide a way to call a specific function on completion.
    • Paul
      Paul over 9 years
      Search mozilla developer network for fork() or exec() or pthread() and you will turn up empty. Why? Because support for child processes and threads is not a standard feature for browser javascript. Web workers is an experimental feature that is supposed to create additional processes that can communicate but do not share scope. Simultaneously running CPU code as you propose isn't supported. Practically all of the "async" JS code cited is about I/O events. On I/O: blah()
  • user1717828
    user1717828 over 9 years
    Thank you for putting such work into your answer, but (like you mentioned in a comment) the for loop was just a dummy function to emulate something that takes a long time. Unless I misunderstand something, this code is only valid for that special case.
  • Alnitak
    Alnitak over 9 years
    @user1717828 oh well. The short answer is, you can't just write your three lines like you have and expect it to work - you have to call your long running task (asynchronously) and then arrange for another function to be called when that completes as I have done with the finished callback in my yieldingLoop example. The original program flow will carry on uninterrupted.
  • Rami Alloush
    Rami Alloush over 4 years
    Can you draw something on the screen during the execution?
  • sgrubsmyon
    sgrubsmyon over 3 years
    I prefer the clarity of this answer over @Alnitak's. But, as @Alnitak pointed out, it's worth noting that one can also use setTimeout(..., 0) to avoid unnecessary waiting time. It's still non-blocking!
  • Niso
    Niso about 3 years
    Ryan, Can you please share links or explain what does callback(i,true) and callback(i,false) do? I searched but could not find exactly what we are calling here.
  • Osei-Owusu
    Osei-Owusu over 2 years
    I agree, setTimeout(..., 0) helps to avoid unnecessary delays when the Event Call Stack is free.
  • Rohit Saini
    Rohit Saini almost 2 years
    setTimeout(callback, 0) will print the same output without waiting for unwanted waiting time over here for testing purposes.