2

If I have not mistaken, javascript callbacks are used with non-blocking functions. (like reading data from a file or getting data from the server).

Now what makes a javascript function non-blocking? what if I want to write a non-blocking javascript function? what is the main construct which defines a non-blocking javascript function.

In the following code, ready , click , slideUp are used as non-blocking functions. How did they become non-blocking functions?

$(document).ready(function(){
    $("button").click(function(){
        $("p").slideUp(2000, function(){
            $("p").slideDown(2000);
        });
    });
});
DesirePRG
  • 6,122
  • 15
  • 69
  • 114

3 Answers3

4

A non-blocking function is any function that sets up an operation, starts that operation and then uses asynchronous resources to manage finishing the operation in the background. Asynchronous resources in the browser are things like system timers, ajax calls, CSS animations, webWorkers, etc...

In the code example you have in your question, both .slideUp() and .slideDown() are jQuery animations that use timers to do a little movement on each timer tick. They are asynchronous for that reason.

You can also execute some types of Javascript code in a webWorker (a separate thread). webWorkers in the browser are very limited in what they can do (they can't touch the DOM at all, for example), they must be loaded from entirely separate scripts, they can't share any variables with your main javascript and they can only communicate with the main javascript via a message passing scheme. But, you can run some types of Javascript in another thread using webWorkers. Here's a summary of webWorkers on MDN.

You can't literally make your own code just magically be asynchronous because a Javascript thread of execution runs until completion in Javascript and then when it's done, the next event in the event queue is processed. You can sometimes simulate "background processing" by doing pieces of your work in small chunks on a timer. This allows other operations (user event processing, other timer events, etc...) to be interwoven with your own execution, but it requires writing your code in an entirely different fashion so it can do work in small chunks on a timer, not just serial execution.

Here are some useful references:

Best way to iterate over an array without blocking the UI

How does JavaScript handle AJAX responses in the background?

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Web Workers introduced in HTML5 that make javascript operations asynchronous.

What is a Web Worker?

When executing scripts in an HTML page, the page becomes unresponsive until the script is finished.

A web worker is a JavaScript that runs in the background, independently of other scripts, without affecting the performance of the page. You can continue to do whatever you want: clicking, selecting things, etc., while the web worker runs in the background.

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93
0

Javascript is single-threaded. So you can't really have a non-blocking function unless you return from your function and then come back to it after an interval. In multi-threaded languages you could do this with something like Thread.sleep(interval). In Javascript, you can use setInterval(function, timeoutInMs) or setTimeout(function, timeoutInMs) to invoke your function periodically. Here's a simple demo that demonstrates the concept:

    <html>
     <head>  
      <style type="text/css">
       #slidingdiv
       {
        background-color: red;
        position: absolute;
        top: 0;
        left: 0;
        width: 150px;
        height: 150px;
       }
      </style>
     </head>
     <body>
      <div id="slidingdiv">
       Sliding Div
      </div>
      
      <script type="text/javascript">
       var slidingDiv = document.getElementById("slidingdiv");
       var divTop = 0;
       
       function slideDown()
       {
        divTop++;
        slidingDiv.style.top = divTop + "px";
        if(divTop < 150)
        {
         // Move the div down 1px every 50ms until it's 150px from the top
         setTimeout(slideDown, 50);
        }
       }
       
       // Start sliding immediately
       slideDown();   
       
       // Change the text in 2 seconds, while the div is still moving, to show
       // that the slideDown method isn't "blocking"
       setTimeout(function() 
        { 
         slidingDiv.innerHTML = "Text Changed"
        },
        2000
       );
      </script>
     </body>
    </html>
Joshua Carmody
  • 13,410
  • 16
  • 64
  • 83