0

Suppose I have two lines of code, code1 and code2, of which both are very fast-runned:

$(function(){
    var flag=0
    var fistElement=$("#someHTML");
    var secondElement=$("#someOtherHTML");

    fisrtElement.append(secondElement);  //code1
    flag=1                               //code2
})

Since both lines of codes(code1 and code2) I would assume could be finished instantly, is there probabilities that the flag update(code2) finished before the html update(code2)? Although normally when I test it with a few examples, the code1 always finished before the code2.

badbye
  • 299
  • 2
  • 12
  • 1
    No, the above code is procedural – Phil Aug 01 '16 at 05:21
  • 1
    javascript will wait for code1 to finish before executing code 2 – Luthando Ntsekwa Aug 01 '16 at 05:22
  • 1
    this code doesn't execute asynchronously – madalinivascu Aug 01 '16 at 05:22
  • 1
    @madalinivascu not *"**only** ajax*". There are several asynchronous operations available in JavaScript – Phil Aug 01 '16 at 05:23
  • 1
    the .append() function is synchronous - see http://stackoverflow.com/questions/6068955/jquery-function-after-append – abagshaw Aug 01 '16 at 05:23
  • code 1 will always execute first. – Naveen Aug 01 '16 at 05:24
  • 1
    @abagshaw: It can be stated more strongly than that. _Every_ JavaScript function or statement is synchronous, in the sense that the following line of code _in the same function_ will not be executed until the previous one completes. There are no exceptions to this rule. Now of course a function like `setTimeout()` or an AJAX call may trigger some _other_ code to be run at a later time, but that asynchronously executed code is always in a different function. It may be another function nested inside the current one (a very common case), but it is always a _different_ function. – Michael Geary Aug 01 '16 at 05:38
  • _"Suppose I have two lines of code, code1 and code2, of which both are very fast-runned"_ What is the actual `javascript` used? – guest271314 Aug 01 '16 at 05:43
  • @guest271314: It doesn't actually matter what the specific JavaScript code is here. One statement will always execute and finish before the next statement is executed, regardless of the actual code. – Michael Geary Aug 01 '16 at 09:53
  • I should add that async/await changes everything, but in my comments above I'm talking about present-day JavaScript, not future JavaScript. – Michael Geary Aug 01 '16 at 09:54

2 Answers2

3

JS is procedural code and it means it's executed line by line (except few cases where code is executed asynchronous).

This means that your code will always be executed in same order => code1 will always be executed before //code2

Justinas
  • 41,402
  • 5
  • 66
  • 96
  • Surely I know code1 would **START** before code2, but the point of my doubt is that whether code1 **FNISH** before code2 – badbye Aug 01 '16 at 06:38
  • @badbye By saying `executed` I mean from **start** to **finish** – Justinas Aug 01 '16 at 06:41
  • This might be a counterexample to your argument:
    bonjour
    – badbye Aug 01 '16 at 06:47
  • @badbye Look at `fadeOut` code - it's async function. – Justinas Aug 01 '16 at 06:58
  • How would I know this function is async? – badbye Aug 01 '16 at 07:06
  • @badbye Set `fadeOut` to `30000` and you will see that your browser does not hang for 30s – Justinas Aug 01 '16 at 07:12
  • 1
    @badbye: You may be over-thinking this. In your fadeOut/hide example, the code1 line (fadeOut) runs to completion before the code2 line (hide) starts. However, we need to be clear what this means. The fadeOut _function call_ runs and immediately returns. However, it has also started a timer which calls a _separate function_ periodically. That other function manages the fading. However, it is not part of this code. The fadeOut function itself merely sets up that timer and returns, allowing the next line of code to run. – Michael Geary Aug 01 '16 at 09:45
  • 1
    Is that distinction clear? There is a separation between a function call itself (like your fadeOut call) and other code which it may trigger asynchronously. The fact that the fading takes three seconds doesn't mean that the fadeOut call _itself_ has paused execution. fadeOut does very little work itself and returns almost immediately. The completion of this function call is what allows the next line of code to run. One statement always runs to completion before the next statement starts. – Michael Geary Aug 01 '16 at 09:48
  • 1
    It doesn't make any difference whether the function in code1 is what we may consider an "asynchronous" function. It's not the function _itself_ that is asynchronous, it isn't. The only asynchronous part is _other_ code in a _different_ function that may be called later in response to a timer or other event. – Michael Geary Aug 01 '16 at 09:50
0

Try this:

function foo(callback) {
    //flag=1   //code2
    console.log( "Code 2 executed" )
    callback();
}
foo(function() {
        //fisrtElement.append(secondElement); //code1
    console.log( "Code 1 executed" )  
});

This works, test it IN JSFIDDLE

HERES YOUR SOLUTION. Your code should look like this

$(function(){
    var flag=0
    var fistElement=$("#someHTML");
    var secondElement=$("#someOtherHTML");
    foo(1,function() {
        fisrtElement.append(secondElement); //code1
        //console.log( "Code 1 executed" )  
    });

   function foo(f, callback) {
       flag=f   //code2
       //console.log( "Code 2 executed" )
       callback();
   }
})

Hope it helps. Thanks

Siddhartha Chowdhury
  • 2,724
  • 1
  • 28
  • 46
  • Sorry, I may be wrong, but why moving code to function makes it async? And your code does not make much sense: First you pass `1` as `flag`, than assign 1 to flag, do callback, and than you do the same once more after `foo`. In Fiddle: you first execute `foo` function, log `"Code 2 executed"` and than do callback. No async here. – Justinas Aug 01 '16 at 05:58
  • Sorry I forgot to clean up my code and thanks for the comment. Well just moving a code to function doesnt makes it asynchronous in nature, though my above example is not the best to illustrate the async but callback definitely is a way to achieve it. – Siddhartha Chowdhury Aug 01 '16 at 06:13
  • Actually callback will **not** make it async. `setTimeout` will. Read here: http://stackoverflow.com/questions/9516900/how-can-i-create-an-asynchronous-function-in-javascript – Justinas Aug 01 '16 at 06:18
  • Thanks for sharing the knowledge, I will keep that in mind. But it would be great if you can check some more about callbacks in: http://sporto.github.io/blog/2012/12/09/callbacks-listeners-promises/ **OR** http://cwbuecheler.com/web/tutorials/2013/javascript-callbacks/ **OR** http://recurial.com/programming/understanding-callback-functions-in-javascript/ – Siddhartha Chowdhury Aug 01 '16 at 06:34
  • There are more, you can google it, no offence but I dont care about another accepted solution that says you **cant** achieve asynchronous trait using callbacks, Anyways all this was about a solution, the seeker has asked in this page, and the solution given addresses his problem. Thats all [am closed] – Siddhartha Chowdhury Aug 01 '16 at 06:34
  • @SiddharthaChowdhury: There is nothing asynchronous in your code here or in the fiddle. It is all step-by-step synchronous code that runs in a completely deterministic order. What makes you think it is asynchronous? First you call `foo()`, which (in the fiddle) displays the "Code 2 executed" message, then `foo()` calls the `callback` function you pass it, which displays "Code 1 executed". This is completely synchronous execution. – Michael Geary Aug 01 '16 at 09:59