When is JavaScript synchronous?

When is JavaScript synchronous?

I have been under the impression for that JavaScript was always asynchronous. However, I have learned that there are situations where it is not (ie DOM manipulations). Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous? Does jQuery affect this at all?

Solutions/Answers:

Solution 1:

JavaScript is always synchronous and single-threaded. If you’re executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.

JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won’t interrupt any other code that’s currently running.

JavaScript timers operate with this same kind of callback.

Describing JavaScript as asynchronous is perhaps misleading. It’s more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.

jQuery has an option on Ajax calls to make them synchronously (with the async: false option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it’s problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.

Solution 2:

JavaScript is single threaded and has a synchronous execution model. Single threaded means that one command is being executed at a time. Synchronous means one at a time i.e. one line of code is being executed at time in order the code appears. So in JavaScript one thing is happening at a time.

Execution Context

The JavaScript engine interacts with other engines in the browser.
In the JavaScript execution stack there is global context at the bottom and then when we invoke functions the JavaScript engine creates new execution contexts for respective functions. When the called function exits its execution context is popped from the stack, and then next execution context is popped and so on…

For example

function abc()
{
   console.log('abc');
}


function xyz()
{
   abc()
   console.log('xyz');
}
var one = 1;
xyz();

In the above code a global execution context will be created and in this context var one will be stored and its value will be 1… when the xyz() invocation is called then a new execution context will be created and if we had defined any variable in xyz function those variables would be stored in the execution context of xyz(). In the xyz function we invoke abc() and then the abc() execution context is created and put on the execution stack… Now when abc() finishes its context is popped from stack, then the xyz() context is popped from stack and then global context will be popped…

Related:  Angular js - detect when all $http() have finished

Now about asynchronous callbacks; asynchronous means more than one at a time.

Just like the execution stack there is the Event Queue. When we want to be notified about some event in the JavaScript engine we can listen to that event, and that event is placed on the queue. For example an Ajax request event, or HTTP request event.

Whenever the execution stack is empty, like shown in above code example, the JavaScript engine periodically looks at the event queue and sees if there is any event to be notified about. For example in the queue there were two events, an ajax request and a HTTP request. It also looks to see if there is a function which needs to be run on that event trigger… So the JavaScript engine is notified about the event and knows the respective function to execute on that event… So the JavaScript engine invokes the handler function, in the example case, e.g. AjaxHandler() will be invoked and like always when a function is invoked its execution context is placed on the execution context and now the function execution finishes and the event ajax request is also removed from the event queue… When AjaxHandler() finishes the execution stack is empty so the engine again looks at the event queue and runs the event handler function of HTTP request which was next in queue. It is important to remember that the event queue is processed only when execution stack is empty.

For example see the code below explaining the execution stack and event queue handling by Javascript engine.

function waitfunction() {
    var a = 5000 + new Date().getTime();
    while (new Date() < a){}
    console.log('waitfunction() context will be popped after this line');
}

function clickHandler() {
    console.log('click event handler...');   
}

document.addEventListener('click', clickHandler);


waitfunction(); //a new context for this function is created and placed on the execution stack
console.log('global context will be popped after this line');

And

<html>
    <head>

    </head>
    <body>

        <script src="program.js"></script>
    </body>
</html>

Now run the webpage and click on the page, and see the output on console. The output will be

waitfunction() context will be popped after this line
global context will be emptied after this line
click event handler...

The JavaScript engine is running the code synchronously as explained in the execution context portion, the browser is asynchronously putting things in event queue. So the functions which take a very long time to complete can interrupt event handling. Things happening in a browser like events are handled this way by JavaScript, if there is a listener supposed to run, the engine will run it when the execution stack is empty. And events are processed in the order they happen, so the asynchronous part is about what is happening outside the engine i.e. what should the engine do when those outside events happen.

Related:  How do I send an AJAX request on a different port with jQuery?

So JavaScript is always synchronous.

Solution 3:

JavaScript is single-threaded, and all the time you work on a normal synchronous code-flow execution.

Good examples of the asynchronous behavior that JavaScript can have are events (user interaction, Ajax request results, etc) and timers, basically actions that might happen at any time.

I would recommend you to give a look to the following article:

That article will help you to understand the single-threaded nature of JavaScript and how timers work internally and how asynchronous JavaScript execution works.

async

Solution 4:

To someone who really understands how JS works this question might seem off, however most people who use JS do not have such a deep level of insight (and don’t necessarily need it) and to them this is a fairly confusing point, I will try to answer from that perspective.

JS is synchronous in the way its code is executed. each line only runs after the line before it has completed and if that line calls a function after that is complete ect…

The main point of confusion arises from the fact that your browser is able to tell JS to excute more code at anytime (simmlar to how you can excute more JS code on a page from the console). As an example JS has Callback functions who’s purpose is to allow JS to BEHAVE asynchronously so further parts of JS can run while waiting for a JS function that has been executed (I.E. a GET call) to return back an answer, JS will continue to run until the browser has an answer at that point the event loop (browser) will execute the JS code that calls the callback function.

Related:  Highcharts DateTime Localization

Since the event loop (browser) can input more JS to be executed at any point in that sense JS is asynchronous (the primary things that will cause a browser to input JS code are timeouts, callbacks and events)

I hope this is clear enough to be helpful to somebody.

Solution 5:

JavaScript is always synchronous and single threaded. There are only a few functions that make it behave asynchronously. e.g connecting to the database, making an API request, calling the setTimeOut function, etc.

console.log("1");
function taketime(){
   for(var i=0;i<1000000;i++){ if(i==1000000) console.log(i);}
}
taketime();
console.log("2");

At first “1” will get printed, the main thread blocks until it completed the taketime() function and in the end, “2′ will get printed.

If JS were to be asynchronous, then the output would be

1
2
10000000

Solution 6:

lol!
DEMO https://jsfiddle.net/9vs1gbtq/
For this affirmation : “JavaScript is always synchronous and single-threaded. If you’re executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.”

my answer is :

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus,the best editor in the World">
  <title>jQuery interval plug-in</title>
  <style type="text/css">
    p{font-size:24px;color:red}
  </style>
 </head>
 <body>
<p id="thread0">0</p><p id="thread1">0</p>
<p id="thread2">0</p><p id="thread3">0</p>
<p id="thread4">0</p><p id="thread5">0</p>
<p id="thread6">0</p><p id="thread7">0</p>
<p id="thread8">0</p><p id="thread9">0</p>

 <!-- these are multiple choises to jquery or zepto (local or from cdns) -->

<!-- 
i am using these in xampp ,under windows server:

<script src="../js/zepto.min.js"></script>
 <script src="../js/jquery.js"></script>  

-->


<!-- 
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.0.js"></script>
<script src="https://code.jquery.com/jquery-3.4.0.slim.js"></script>
<script src="https://code.jquery.com/jquery-3.4.0.slim.min.js"></script>
-->


<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>
<!-- (Zepto.js is the equivalent of jQuery,but faster ,created by  genious :
               thanx Thomas Fuchs and contributors!!!
) -->

<!--
<script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.js"></script>
 -->



 <!-- 


 -->


<script>
//THIS IS MY PLUGIN ON https://github.com/xpectmore/jQuery-Interval
    //start plug-in
jqzp=function(){console.log('jQuery/Zepto not found: please enable one of them!');}
if (typeof($) == 'undefined'){  jqzp(); }else $( document ).ready(function(){
    var _sI=[];
    $.interval=function(){
        if (arguments.length==3){
            if (_sI[arguments[0]]== undefined){
                _sI[arguments[0]]={};
            }else{
                clearInterval(_sI[arguments[0]].reg);
            }
            _sI[arguments[0]].fn=arguments[2];
            _sI[arguments[0]].t=arguments[1];
            _sI[arguments[0]].reg=setInterval(arguments[2],arguments[1]);
        }else if (arguments.length==1){
            clearInterval(_sI[arguments[0]].reg);
        }else{
            console.log('The number of the arguments should be 3 or 1');
            console.log('$.interval("id",time_in_milliseconds,function(){do_what_you_want();})');
            console.log('to stop that use: $.interval("id")');
        }
    }
});
//stop plug-in
</script>



<script>


$( document ).ready(function(){


    var th0=0;
    $.interval('th0',500,function(){
        $('#thread0').text(th0);
        th0++;
    });
    var th1=0;
    $.interval('th1',1000,function(){
        $('#thread1').text(th1);
        th1++;
    });
    var th2=0;
    $.interval('th2',1500,function(){
        $('#thread2').text(th2);
        th2++;
    });
    var th3=0;
    $.interval('th3',500,function(){
        $('#thread3').text(th3);
        th3++;
    });
    var th4=0;
    $.interval('th4',1000,function(){
        $('#thread4').text(th4);
        th4++;
    });
    var th5=0;
    $.interval('th5',1500,function(){
        $('#thread5').text(th5);
        th5++;
    });
    var th6=0;
    $.interval('th6',500,function(){
        $('#thread6').text(th6);
        th6++;
    });
    var th7=0;
    $.interval('th7',1000,function(){
        $('#thread7').text(th7);
        th7++;
    });
    var th8=0;
    $.interval('th8',1500,function(){
        $('#thread8').text(th8);
        th8++;
    });
    var th9=0;
    $.interval('th9',500,function(){
        $('#thread9').text(th9);
        th9++;
    });

});


</script>
 </body>
</html>