greenn
greenn

Reputation: 309

Callback function clarification

I have a javascript callback function setup like this

function myFunction(callback){

    $('meta[name="viewport"]').prop('content', 'width=1440');
    //other code
    callback()
}

function otherFunction(){
   //some async operation
}

myFunction(otherFunction)

Does this code ensure that my otherFunction does not run before the viewport is changed and other code above it is implemented?

Upvotes: 2

Views: 141

Answers (4)

Shahid Kamal
Shahid Kamal

Reputation: 440

Yes it'll ensure that myFunction will run after all the code above it if and only if the code above callback() is also synchronous. In example it's ensured that callback() will only be executed once viewport has been changed.

Upvotes: 0

Manikant Gautam
Manikant Gautam

Reputation: 3581

Here is best way to look into it. Here i have added a statement just before the callBack function . You can see the console log even after otherfunction execution. So it entirely depends upon whether you are using synchronous or asynchronous code before the function invocation.

function myFunction(callback){

    $('#ipt').val(callback.name);
    //other code
    setTimeout(function(){console.log('hello')},5000)
    callback()
}

function otherFunction(){
   alert( $('#ipt').val());
}

myFunction(otherFunction)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="ipt" placeholder="Dummy text"/>

Upvotes: 1

Willem van der Veen
Willem van der Veen

Reputation: 36580

Asynchronous callback functions will always run after all synchronous code has been completed. This is because JS has something called the event loop which looks the following way:

enter image description here

Whenever we do asynchronous operation often this is associated with a Web API. This web API is abstracted away from us. We don't need to know how the browser implements this feature (which probably is written in C++ as part of the browser). However, we are interested in the value of operation or eventual return value.

So what the browser does is whenever the webAPI's are finished the callback associated with it is pushed in the callback queue. Then whenever the stack is empty the event loop will push an function on the stack.

This is why asynchronous operations will always be performed last, because the event loop will wait for the stack to be empty before pushing an item on it.

Upvotes: 1

Pedro Brost
Pedro Brost

Reputation: 1452

If all the code above the callback call is synchronous, then yes, otherFunction will run after all the code above.

Upvotes: 4

Related Questions