javascriptasynchronouscallbacknonblocking

How to make non-blocking javascript code?


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.


Solution

  • 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.