2

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?

1
  • 2
    There's nothing asynchronous here, so yes myFunction should change the meta tag before the callback is called. Commented Sep 14, 2018 at 11:23

4 Answers 4

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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"/>

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.