简体   繁体   中英

Asynchronous JavaScript using Callbacks

I am new to JavaScript and from various resources i have read that JavaScript functions are Asynchronous if they are coupled with Callbacks. After searching rigorously for 10+ days on web i could not find an explanation on how Callbacks in JavaScript run Asynchronously. Some examples with AJAX are given but they do not provide a clear answer, can anyone explain how callbacks in JavaScript run Asynchronously for the below code?

function myFunc(a,b,callback){
    var callbackValue = callback();
    var add= a+b;
    var subt= a-b;
    var mult= a*b;
    var div= a/b;
    ...
    ...
    ...
    ...
    ...
    var totalValue= add+callbackValue;
}

function myFunc(a,b,function(){//complex scientific operation which takes 10 secs });

As i am using a callback in "myFunc" in the above code, does that mean that when callback() is invoked in "myFunc", it runs asynchronously and the program flow continues with var add= a+b; var subt= ab; ......... ....... without waiting for result of callback();?

asynchronous - not occurring at the same time.

synchronous means that the page will have to wait while JavaScript executes. With asynchronous the page does not have to wait for the execution of jaJavaScript

Yes and no. If you don't use setTimeout/setInterval, then it runs synchronously.

// alert after 5 seconds
function func(f) {
    f();
    alert('Hello');
}

func(wait5);

But if you use setTimeout, it can run in a separate execution context. I'd Google this, since it's rhetorical to explain.

// alert immediately, then wait 5 seconds
function func(f) {
    setTimeout(f, 0);
    alert('Hello');
}

func(wait5);

Of course, wait5 in this case would be a function that waits 5 seconds. You can create this function if you'd like, just run a while loop until 5 seconds has elapsed ( check using new Date().getTime() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM